Loading…
Loading…
Charting your lesson…
Opening your lesson…
Sliding Window (Fixed and Variable)
Lesson 3 of 8
6 steps•about 11 min•11 flashcards
Step 1/ 61 min
Whenever a question asks about the "best contiguous subarray or substring" — longest, shortest, maximum sum, at most K distinct — the sliding window turns a recompute-everything O(n²) or O(n·k) approach into one O(n) pass.
Core idea: maintain a contiguous window [left, right] and a running summary (sum, count, frequency map). As right expands you add one element; when the window breaks a constraint you shrink from left, removing elements. Nothing is recomputed from scratch.
Step 2/ 61 min
"Maximum sum of any subarray of length k": compute the first window's sum, then slide by adding the incoming element and subtracting the outgoing one.
sum = sum(a[0..k-1]); best = sum
for right in k..n-1:
sum += a[right] - a[right-k]
best = max(best, sum)
Each step is O(1), so the whole scan is O(n), versus O(n·k) if you re-add k elements each time.
Here the window grows and shrinks to satisfy a constraint. Pattern for "longest substring with at most K distinct characters":
left = 0; freq = {}
for right in 0..n-1:
freq[a[right]] += 1
while len(freq) > K: # constraint broken → shrink
freq[a[left]] -= 1
if freq[a[left]] == 0: del freq[a[left]]
left += 1
best = max(best, right - left + 1)
The inner while looks nested, but left only ever moves forward and never past right. Across the entire run, left advances at most n times total. So the amortised work is O(n) time; space is O(K) or O(alphabet) for the map.
Step 3/ 61 min
Longest substring without repeating characters in "abcabcbb". Expand right, tracking last-seen positions. At the second a (index 3), the window abc would repeat a, so move left past the old a. Windows: abc (len 3) is the max. Answer 3. Each character enters and leaves the window once → O(n).
Step 4/ 61 min
Cue phrases: "contiguous", "subarray/substring", "longest/shortest/maximum", "at most / exactly K". Fixed window when the length is given; variable window when you optimise length under a constraint. "Exactly K" is often computed as atMost(K) − atMost(K−1).
Step 5/ 61 min
while, not if: several elements may need removing after one expansion.Applying a sliding window to problems with negative numbers where you want a target sum. Shrinking assumes adding elements only increases the sum; with negatives that monotonicity breaks. Use prefix sums + hashing there instead.
Step 6/ 6· Worked examples1 min
Problem
Find the maximum sum of any contiguous subarray of size k = 3 in [2, 1, 5, 1, 3, 2].
Try it on paper first.
Recall
Keep this
Sliding window is the go-to pattern for "contiguous subarray/substring" problems. It maintains a window [left, right] and, instead of recomputing from scratch, updates an aggregate as the window slides — collapsing O(n²) or O(n·k) brute force into a clean O(n) pass.
There are two kinds:
Efficiency: right advances n times and left advances at most n times total, so it is O(n) even though it looks nested.
| Problem type | Window | Time | Space |
|---|---|---|---|
| Max sum of k-length subarray | fixed | O(n) | O(1) |
| Longest substring w/o repeat | variable | O(n) | O(k) alphabet |
| Min window covering target | variable | O(n) | O(k) |
| Count anagrams / permutations | fixed | O(n) | O(1) |
Longest/shortest/count of subarrays meeting a sum, distinctness, or frequency constraint. Interviewers want the O(n) window plus a clear invariant for when you shrink versus expand.
Slide a window and update an aggregate incrementally. Fixed size → add/remove one per step; variable size → expand-then-shrink on a constraint. O(n) time, O(1)–O(k) space. Beware negatives breaking the monotonic shrink.
You've read 0 of 6 steps
Now lock it in — questions straight after reading are what make it stick.