Pattern

Sliding window

Maintain a contiguous range with two pointers, growing and shrinking it instead of rescanning from scratch.

What it is

A sliding window keeps a contiguous range of a sequence (an array, a string, or a stream of timestamped events) between two pointers and moves those pointers forward as some condition changes, so the window only ever expands on the right and contracts on the left. The payoff is turning an O(n²) "check every subarray" approach into O(n), because the window's running state (a sum, a character count map, a count of distinct values) is updated incrementally rather than recomputed from scratch each time the window changes.

When it applies

Tells in the problem

The classic mistake

The window's internal state and its length get out of sync: a solution grows the right pointer, updates a frequency map, but only shrinks the left pointer far enough to make the window "look" valid without re-checking that every count is still within bounds, so it silently accepts a window with e.g. three distinct characters when the limit was two. This shows up as an off-by-one in the answer that only appears on inputs where the window needs to shrink by more than one step at once. The fix is to shrink in a while loop that re-checks the actual condition after each removal, not an if that assumes one step is enough — and to update the running state (decrementing a count, possibly deleting a key at zero) on every removal, not just moving the pointer.

Questions to start with

All 14 sliding window questions

Problem statement, examples and hints are free on every page; the worked approach, solution and tests are in the company guides.

Free starter pack

13 must-tier questions with full solutions

Sign in with an email — no purchase — and read them in the full reader.

No password, no spam. One sign-in email; you can read the pack in the full reader.