Sliding Window
O(n)
Expand the right edge; shrink the left only while the window violates the rule. Track the best as you go.
0/36 solved
Recognise it
The signal
Longest/shortest/count of a contiguous subarray or substring under a monotone rule (sum, ≤k distinct, no repeats), or a fixed size k.
1Brute force
Enumerate all O(n2) windows and recompute each summary.
2The observation
Recomputing the window summary: an incremental add/remove updates it in O(1), and monotonicity means l never moves left.
3Why it works
For each r, l is the smallest index with [l, r] valid, and l never moves back, so each element enters and leaves once: O(n).
Reach for it when
- +You want the longest/shortest/max/min contiguous subarray or substring under a constraint (sum, distinct count, no repeats).
- +A fixed window of size k — max average, every window's sum, anagram/permutation matching.
- +The brute force is 'try every subarray' and the per-window check can be updated incrementally instead of recomputed.
Not when
- ×Elements can be skipped (subsequence, not contiguous)use Subsequence DP
- ×Negative numbers with a sum target: growing can shrink the sum, validity isn't monotoneuse Prefix sum + hash map
- ×Pairs from a sorted array hitting a targetuse Opposite-end two pointers
- ×"Exactly K" constraint (exact counts aren't monotone)use atMost(K) − atMost(K−1) with two windows
- ×You need the max/min of each windowuse Monotonic deque, not a counter
- ×Window state can't be kept by simple add/removeuse Dynamic programming
Intuition
A window is just a contiguous slice of the array — everything from index l to index r, inclusive. Picture a cardboard frame laid over a row of numbers; only what's inside the frame counts right now.
Read the full intuition
Two finger-indices hold the frame's edges. The whole trick is: grow the right edge to add elements, shrink the left edge to remove them — and the elements between them are "currently in play." Instead of re-scanning every possible slice (O(n²)), each element is added once and removed at most once, so you sweep the array a single time.
The rhythm (memorise this):
rsteps forward → bringarr[r]into the window (update your running total / counts).whilethe window breaks the rule → steplforward, removingarr[l]from the window.- The window is now valid → record the answer (its length, or its sum).
Walk "abcabcbb", "longest substring with no repeat":
- r=0 'a' → window "a", best 1.
- r=1 'b' → "ab", best 2. r=2 'c' → "abc", best 3.
- r=3 'a' → 'a' already inside! Shrink from left past the old 'a': l moves to 1. Window "bca", best stays 3.
- …it never re-reads anything; l and r each only march rightward.
Two shapes exist. Variable-size: window grows/shrinks to stay valid, you maximise/minimise its length. Fixed-size k: window is always exactly k wide — add
arr[r], and oncer-l+1 > kdroparr[l]and slide.
Why it costs what it costs
Time O(n). r advances n times; l advances at most n times total across the whole run — each element enters and leaves the window once.
Space O(k). the map/counter holds at most the number of distinct elements in the window (≤ alphabet size or k).
Practice
- Maximum Average Subarray IFoundationFoundationEasy
- Longest Substring Without Repeating CharactersApply it · Variable window; shrink while a duplicate exists.Apply itAmazon, AdobeMedium
- Fruit Into BasketsOne change · Validity is 'at most 2 distinct values' tracked by a count map.One changeMedium
- Permutation in StringOne change · Fixed-size window compared by frequency vector.One changeMicrosoft, UberMedium
- Longest Repeating Character ReplacementTwists · Validity uses window length - maxFreq <= k, and maxFreq need not be decreased.TwistsGoogle, UberMedium
- Minimum Window SubstringBranches · Minimise instead of maximise: shrink while VALID.BranchesMeta, AmazonHard
- Subarrays with K Different IntegersBranches · 'Exactly K' instead of 'at most K'.BranchesHard
- Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitCombine · Window validity depends on window max - min.CombineMedium
- Shortest Subarray with Sum at Least KMastery checkMastery checkGoldman Sachs, CitadelHard
- Sliding Window MaximumAmazon, GoogleHard
- PlaylistCSESMedium
- Distinct Values SubarraysCSESMedium
Pitfalls
Classic bugs
- !Shrinking with
ifinstead ofwhile— one removal often isn't enough to restore validity. - !Window length is
r - l + 1, notr - l. - !Not deleting a key when its count hits 0 — the distinct-count check then counts ghosts.
- !Updating
bestin the wrong place: longest-valid after the shrink loop; shortest-valid inside it while still valid. - !Recomputing the window from scratch on each shrink — update the running state incrementally.
Looks like it, isn't
- Subarray Sum Equals K needs Prefix Sum
Why
Negative numbers make window validity non-monotone; count prefix pairs with a hash map. source ↗ - Subarray Sums Divisible by K needs Prefix Sum
Why
Divisibility is not monotone in window size; key prefix sums by residue. source ↗ - Shortest Subarray with Sum at Least K needs Monotonic Deque
Why
Negatives break shrinking; keep a monotone deque of prefix sums. source ↗ - Sum of Subarray Minimums needs Monotonic Stack
Why
No window condition; each element's contribution span comes from previous/next smaller. - Bitwise ORs of Subarrays needs Few Distinct Subarray OR / AND / GCD Values
Why
No window condition. The ORs ending at each index take only O(log V) values; carry that set forward. source ↗
Go deepervariants and techniques · 3 combinations · interviewer follow-ups · resources
Variants and techniques
- Variable, longest-validGrow r; while invalid, shrink l; record max length after the while. Longest substring w/o repeat, longest with ≤k distinct.
- Variable, shortest-validGrow r until valid; then shrink l as far as still-valid, recording min length each step. Minimum Window Substring, min size subarray sum.
- Fixed size kNo while-loop; once
r-l+1 > kdrop exactly one from the left. Max average, sliding window of anagrams. - Count windowsAdd
r - l + 1to an answer each step to count all valid subarrays ending at r (e.g. subarrays with product < k).
Combinations
Sliding Window+Hash Map / Hash Set Lookup
longest/shortest substring with distinct/at-most-K/covers-all-chars condition
- Sliding Window:
- maintains a valid contiguous window
- Hash Map / Hash Set Lookup:
- keeps character/value frequencies for the validity test
Longest Substring Without Repeating CharactersMinimum Window SubstringPermutation in String
Sliding Window+Monotonic Deque
subarray where max - min <= limit, or window extreme queries
- Sliding Window:
- two-pointer window boundaries
- Monotonic Deque:
- O(1) window max/min
Longest Continuous Subarray With Absolute Diff Less Than or Equal to LimitSliding Window MaximumSliding Window Minimum
Probability & Expected-Value DP (linearity of expectation)+1D / Fibonacci-style+Sliding Window
probability over a running total with uniform draws and a stopping threshold
- Probability & Expected-Value DP (linearity of expectation):
- P(i) = (1/W) * sum of P(i - k) over k = 1..W
- 1D / Fibonacci-style:
- the probability DP over points
- Sliding Window:
- keep that sum in O(1) per step
Follow-ups interviewers ask
- 01What if numbers can be negative (sum target)? → the window's monotonicity breaks; switch to prefix sum + hash map.
- 02Fixed size k vs variable size? → fixed drops exactly one element per step (no while-loop); variable grows/shrinks to stay valid.
- 03Count all valid windows, not the longest? → add
r - l + 1each step (subarrays ending at r). - 04What if the alphabet is huge / unicode? → use a hash map of counts instead of a fixed 26-array.
State table
| r | char | window | l moves? | window len | best |
|---|---|---|---|---|---|
| 0 | a | a |
— | 1 | 1 |
| 1 | b | ab |
— | 2 | 2 |
| 2 | c | abc |
— | 3 | 3 |
| 3 | a | bca |
l→1 (drop dup a) | 3 | 3 |
| 4 | b | cab |
l→2 | 3 | 3 |