synopsis · Linear patterns · chapter 13
Sliding Window
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A window
[left, right]over a contiguous slice plus a tiny summary of it. Each move adds one element and removes one, so the whole scan is O(n). - use it when
"Contiguous subarray / substring" + longest, shortest, max or min; "of size k"; "at most k"; an anagram or permutation inside a longer string.
- template
Fixed: build the first k, then
sum += nums[r] - nums[r - k];. The element leaving is alwaysnums[r - k]. - template
Variable:
for (r…) { add(r); while (invalid) remove(l++); best = max(best, r - l + 1); }— grow, shrink while invalid, record. - cost
O(n):
rightmoves n times,leftat most n times. Space: O(1) for a sum, O(σ) forint[26]/int[128], O(k) for a deque. - trap
Negative numbers break sum windows: removing one can raise the sum. Use prefix sums + a
HashMapinstead. - trap
Longest → record after the shrink loop. Shortest → record inside it, before removing
nums[left]. - trap
Shrink with
while, notif: one new element can force several removals. - pro tip
"Exactly k" =
atMost(k) - atMost(k - 1). Max or min of every window → a monotonicArrayDequeof indices.
Shaky on a card? Open the chapter or flip its recall cards.