Sliding Window
Medium+70 XPGlide a contiguous window across an array or string, updating the answer as it moves — one pass instead of re-checking every range.
Where it breaks
A sliding window only works when the answer must be a contiguous run.See what happens when you don't.
No visualization loaded.
Watch
—
Press Run to begin.
A sliding window is a little box that covers a few cells in a row (a 'contiguous' run) and then glides to the right. Instead of re-counting a whole stretch every time you move, you just update for the one cell that ENTERS the window and the one that LEAVES it. Two edges — call them L (left) and R (right) — mark the box. Grow it by stepping R right; shrink it by stepping L right. Because neither edge ever walks backward, the whole thing finishes in one smooth pass.
▸What exactly IS a sliding window?
It's a range of cells that sit next to each other — like a highlighter laid over a few letters in a word. The left edge L and right edge R say where the highlighter starts and ends. As you slide it right, letters at the front fall out and new letters at the back come in. The window is the highlighted part; everything outside it you're ignoring for now.
▸When should I reach for a sliding window?
When the question is about a CONTIGUOUS chunk — a substring or a run of array elements that are side by side — and asks for the longest, shortest, or biggest/smallest such chunk. 'Longest substring without repeats', 'max sum of k numbers in a row', 'smallest window containing all these letters' — all sliding-window shaped. If the pieces don't have to be next to each other, it's NOT a window problem.
▸What's the difference between a fixed and a variable window?
A FIXED window is always exactly k cells wide: every time R steps right, L steps right too, so the box stays the same size (great for 'max sum of k in a row'). A VARIABLE window changes size: R keeps growing the box, and you only pull L in when something goes wrong — like a repeated letter — then you shrink just enough to fix it. Same picture, but the variable one stretches and squeezes.
▸Why is this O(n) and not O(n²)?
The slow way re-scans every possible range from scratch: for each start, walk to every end — that's a loop inside a loop, about n×n work (O(n²)). The window never re-scans. L and R each only ever move RIGHT, and each can move at most n steps total. Add those up and you get at most 2n moves — one pass, O(n). The trick is reusing the work you already did instead of throwing it away.
How the work grows
O(n) is fair — grows in step with the data. Each edge (L and R) only moves rightward, at most n steps each — so the whole sweep is a single O(n) pass instead of the O(n²) cost of re-checking every range. You store just the contents of the current window, which is at most k items.
Faint dotted lines = O(1) (flat) and O(n) (straight) for comparison.