Skip to content
Tech Interview Prep
Technical interview guide

Sliding Window

A variable- or fixed-size window over a sequence, expanded and contracted in O(n) total instead of recomputing from scratch.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v7
Editorial status
Reviewed

Scope: Language-neutral, with container costs cited from CPython 3.14 and the C++ standard containers.

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

O(n) total: each index enters once and leaves at most onceO(n)\text{ total: each index enters once and leaves at most once} exactly(K)=atMost(K)−atMost(K−1)\text{exactly}(K)=\text{atMost}(K)-\text{atMost}(K-1) count+=right−left+1\text{count} \mathrel{+}= \text{right}-\text{left}+1 MCQ 1 run: 100,000 adds+99,000 subtracts=199,000 operations, against 100,000×1,000 additions when recomputed\text{MCQ 1 run: } 100{,}000\text{ adds}+99{,}000\text{ subtracts}=199{,}000 \text{ operations, against } 100{,}000 \times 1{,}000 \text{ additions when recomputed}

How it works

yes no Extend: add a[right B Remove a[left Record answer right += 1
  • 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

SituationSliding window?Alternative or note
Contiguous, all values non-negativeYesStandard shrink loop
Values may be negativeNo, shrink rule is unsoundPrefix sums with a hash map
Subsequence, elements need not be adjacentNoDP or patience sorting for LIS
Maximum of every k-length windowYesMonotonic deque, not a heap
Unbounded stream, only the window retainedYesBounded deque; no backward indexing
Time span with bursty arrivalsPartlyTime eviction plus a count cap

Traps interviewers probe

  1. 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.
  2. 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.
  3. Running maximum after the maximum leaves. Maxima have no inverse. Fix: a monotonic deque of indices, evicted by position from the front.
  4. 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.
  5. 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.

  1. Contiguous range, monotone constraint, so one pass works.
  2. Maintain the summary with O(1) add and remove.
  3. Extend the right end, shrink the left while invalid, record after shrinking.
  4. Each index enters and leaves once: O(n) time, O(window) memory.
  5. 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.