Skip to content

Sliding windows: reuse the work you just did

Working knowledgeConcept

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.

Sum every window
best = 0
for i in range(len(a) - k + 1):
best = max(best, sum(a[i:i + k])) # adds k values every time
Slide the window
window = sum(a[:k])
best = window
for r in range(k, len(a)):
window += a[r] - a[r - k] # one in, one out
best = 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.

Biggest sum of 3 neighbours
Step 1 of 8
Best –
8 values, window of 3
40
21
72
13
84
35
66
57
  • 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.

– window sum

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 R one place and add its letter to the counts.
  • Shrink: while the rule is broken, remove s[L] from the counts and move L one 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.

Longest stretch with at most two letters
Step 1 of 13
Best length 0
the string
a0
b1
c2
b3
b4
c5
a6
letter → count in the window
Empty
  • 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.

0 letters in window

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.

Check every substringn(n+1)/2 windows28 windows for 7 letters, each counted from scratch: O(n³) as written, O(n²) with care.
Slide the windowat most 2n movesEach letter enters once and leaves at most once. 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.

two_letters.py
def longest_with_two_letters(s):
counts = {} # letter -> how many times it is in the window
left = 0
best = 0
for right, ch in enumerate(s):
counts[ch] = counts.get(ch, 0) + 1 # grow: take s[right] in
while len(counts) > 2: # broken: shrink from the left
out = s[left]
counts[out] -= 1
if counts[out] == 0:
del counts[out]
left += 1
best = max(best, right - left + 1)
return best
print(longest_with_two_letters("abcbbca"))
Text
$ python3 two_letters.py
5
4

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.

07 Check yourself

Question

A fixed window of width 100 slides one place along an array. How much arithmetic does the new sum take?

Question

For "shortest stretch with sum at least target", which input breaks the grow-and-shrink loop?

Question

On a string of n letters, at most how many times can L move in the variable-window loop, over the whole run?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?