Sliding windows: reuse the work you just did
Questions about neighbouring values, such as the best three in a row or the longest stretch without a repeat, tempt you to check every range from scratch. Neighbouring ranges share almost everything, so move the edges and update what changed: grow the right, shrink the left, never re-scan the middle.
01 Neighbouring ranges share most of their values
Take [4, 2, 7, 1, 8, 3, 6, 5] and ask for the biggest sum of three neighbours. The direct way sums every group of three: 4 + 2 + 7, then 2 + 7 + 1, then 7 + 1 + 8. Look at the first two: they share 2 + 7, and the loop adds it twice.
best = 0for i in range(len(a) - k + 1):best = max(best, sum(a[i:i + k])) # adds k values every time
window = sum(a[:k])best = windowfor r in range(k, len(a)):window += a[r] - a[r - k] # one in, one outbest = max(best, window)
Both print 17. The left one does k additions per window, so O(n·k) in all. The right one keeps the sum and fixes it up with one value in and one out, so O(n) whatever k is.
02 A window of fixed width
Picture the window as a frame over three cells. Sliding it right changes exactly two cells: one enters on the right, one leaves on the left. The sum only needs to hear about those two.
- in the window
- just came in
- just went out
- best window
Find the three neighbours with the biggest sum. The window has not been placed yet.
03 Grow the right edge, shrink the left
Most window problems do not fix the width. They give a rule instead, and ask for the longest (or shortest) stretch that keeps it. Here the rule is at most two different letters, on the string abcbbca.
- Grow: move
Rone place and add its letter to the counts. - Shrink: while the rule is broken, remove
s[L]from the counts and moveLone place. - Record: once the window is valid again, compare its length with the best.
The counts in the map are the reused work. They always describe exactly the letters between L and R, so checking the rule is len(counts) > 2, not a scan of the window.
- in the window
- just came in
- just dropped
- count just changed
- count hit 0
Find the longest stretch with at most two different letters. The window is empty and so is the map of counts.
04 Why it is O(n), not O(n²)
The inner while loop makes it look quadratic. Count moves instead of loops: R passes each index once, and L passes each index at most once, because neither edge ever moves back. In the trace that was 7 grows and 5 shrinks, 12 moves for 7 letters.
O(n³) as written, O(n²) with care.O(n) time, and the map holds at most three keys.That is the meaning of never re-scanning the middle: everything inside the window is summarised by the map, and every move updates the summary in constant time.
05 The loop in code
This is the variable window as code. Most window problems keep this shape and change three things: what the map stores, the rule in the while, and what you record.
For a shortest stretch, the record moves inside the while: you record each valid window and then shrink to see whether a smaller one still works.
06 When a window works, and when it breaks
Shrinking from the left is safe only if the rule is monotone: if a window breaks it, every bigger window around it breaks it too. A window with three letters still has at least three when it grows. Check this before you reach for a window.
[5, -3, 8, 2], sum ≥ 10Negative numbersWith negatives, dropping a value from the left can raise the sum, so "too small, grow" and "big enough, shrink" stop being true. Prefix sums handle these instead: with a hash map for an exact sum, with a monotonic deque for "at least".while len(set(s[left:right + 1])) > 2:Re-scanning the window anywayBuilding a set from the slice reads the whole window on every check, which puts the O(n·k) cost straight back. Keep counts and update them by one.counts[out] -= 1Leaving zero counts in the mapWithout del counts[out] the key stays with count 0, len(counts) never comes down, and the loop shrinks the window to nothing.window_max -= a[r - k]Undoing a maximumA sum can be undone by subtracting; a maximum cannot. When the biggest value leaves, you need the next biggest, which is why Sliding Window Maximum keeps a deque of candidates.