Overview
Curated: · Written: · Reviewed:
Sliding Window
In one line
Keep a summary of a contiguous range that updates in O(1) when either end moves, so a subarray question costs one pass. Reach for it when the constraint moves one way as the range grows (non-negative sums, distinct counts, a flip budget) and the answer concerns contiguous ranges.
Key definitions
- Fixed window: length k is given; both ends move together, one add and one remove per step.
- Variable window: the right end always advances; the left end advances only while the constraint is violated.
- Monotone constraint: once a window violates it, every longer window does too. For sums this requires non-negative values.
- Validity invariant: the window satisfies the constraint at the moment the answer is read.
- Monotonic deque: indices kept in decreasing value order, so the front is the current window maximum.
- At-most decomposition: exactly K equals atMost(K) minus atMost(K-1).
Formulas and complexity
How it works
- Each boundary move touches one element, so the total number of moves is at most 2n.
- Shrink with while, not if; a single removal can leave the window invalid.
- Record after the shrink loop. Recording inside it reports a window that breaks the constraint.
- Store the start and length together with the best value, because the pointers keep moving.
When to use and when not to
| Situation | Sliding window? | Alternative or note |
|---|---|---|
| Contiguous, all values non-negative | Yes | Standard shrink loop |
| Values may be negative | No, shrink rule is unsound | Prefix sums with a hash map |
| Subsequence, elements need not be adjacent | No | DP or patience sorting for LIS |
| Maximum of every k-length window | Yes | Monotonic deque, not a heap |
| Unbounded stream, only the window retained | Yes | Bounded deque; no backward indexing |
| Time span with bursty arrivals | Partly | Time eviction plus a count cap |
Traps interviewers probe
- Recording before the window is valid. On a = [10, 10, 10, -100, 5, 5, 5, 5] with a width-4 sum, the loop that records during priming prints 30 (a prefix of length 3). The correct maximum is 20. Fix: prime the window, then record only when it is full.
- Shrinking on negatives. On a = [5, 5, -10, 5] with k = 5, the shrink loop returns 3. The correct longest span with sum at most 5 is 4, because the whole array sums to 5 and only growing reaches it. Fix: prefix sums with a hash map.
- Running maximum after the maximum leaves. Maxima have no inverse. Fix: a monotonic deque of indices, evicted by position from the front.
- Removing from the front of a list. Python's list.pop(0) and del q[0] are O(n) per call, which quietly makes the pass quadratic. Fix: collections.deque with popleft.
- Counting exact-K windows in one pass. A shrink rule has no consistent direction for exactly K. Fix: atMost(K) minus atMost(K-1), checked by brute force on small inputs.
Interview tips
Opening. Name the two preconditions first: the range is contiguous, and the constraint is monotone under growth. Then state what the summary is and that add and remove are O(1).
Follow-ups to expect.
- What if values can be negative? Switch to prefix sums with a hash map.
- What if you need the window itself, not its length? Capture boundaries at the optimum.
- What if the input is a stream? Retain only the window, and say so before proposing random access.
- Why not a heap for the maximum? Lazy deletion can keep all n elements alive, where the deque holds only k.
- Why is the time window risky? Under a 10x burst it holds 10x the entries, so bound it by count too.
30-second outline.
- Contiguous range, monotone constraint, so one pass works.
- Maintain the summary with O(1) add and remove.
- Extend the right end, shrink the left while invalid, record after shrinking.
- Each index enters and leaves once: O(n) time, O(window) memory.
- The case that breaks it is a negative value, and prefix sums replace it.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.