Sliding Window
Read a little, play a little. No scary maths, and no rush.
The conveyor belt
Imagine a conveyor belt of numbers and a fixed-size frame sliding across it: at each step one value enters the frame, one leaves. Instead of re-adding everything (O(nk)), you adjust by the difference (O(n)). That sliding frame — and its stretchy cousin that grows and shrinks — handles a huge family of "contiguous subarray/substring" problems.
Fixed window: maximum average
"Best average of any k consecutive elements": slide, don't recompute.
def max_avg(a, k):
cur = best = sum(a[:k])
for i in range(k, len(a)):
cur += a[i] - a[i - k] # enter right, leave left
best = max(best, cur)
return best / k
Each step is O(1). Whenever the prompt says "subarray of size K," your hand should write this loop.
Dynamic window: longest without repeats
Now the frame stretches: expand the right edge, and whenever the window becomes invalid (a duplicate!), shrink the left past the trouble. A map of last-seen positions makes the shrink O(1):
def longest_unique(s):
seen, l, best = {}, 0, 0
for r, ch in enumerate(s):
if ch in seen and seen[ch] >= l:
l = seen[ch] + 1 # jump left past the previous twin
seen[ch] = r
best = max(best, r - l + 1)
return best
The >= l check matters: a twin outside the current window is ancient history, not a violation.
A trace of the dynamic window
Run longest_unique("abcabcbb"):
- r reaches "a", "b", "c" with no repeats. The window "abc" has length 3.
- r reaches the second "a". Its twin is inside the window, so l jumps past it. The window is now "bca", still length 3.
- The same happens for the next "b" and "c": the window slides to "cab", then "abc".
- The later "b"s force l forward again, and the window never beats 3.
Answer: 3. Each character entered the window once and the left edge only ever moved forward, which is where the O(n) comes from.
The general template
Most dynamic-window problems fit one shape:
l = 0
for r in range(len(s)):
add(s[r]) # grow the window on the right
while window_is_invalid():
remove(s[l]) # shrink from the left until valid again
l += 1
record(r - l + 1) # the window [l, r] is valid here
Only three things change between problems: what "add" and "remove" track, what makes the window invalid, and what you record.
At most K distinct: the bookkeeping
For "longest substring with at most K distinct characters," keep a map from character to count. Adding a character increments its count. When the map holds more than K keys, shrink from the left: decrement the leaving character's count, and delete it from the map when its count reaches zero. Forgetting that deletion is the classic bug, because the map's size then overstates how many distinct characters the window really holds.
Recognizing the pattern
Keywords: "contiguous," "subarray/substring," "longest/shortest with constraint," "at most K distinct." Fixed size → slide arithmetically. Constraint-based → expand/shrink with a map or counter.
When a window does not fit
The pattern needs two things: the answer must be a contiguous range, and you must be able to tell, after each move of an edge, whether to grow or shrink. When values can be negative and the condition is about a sum, adding an element can make the sum go up or down, so there is no reliable rule for moving the edges. Counting subarrays with an exact sum is the standard example, and prefix sums with a hash map handle it instead.
Remember this
- Never recompute a window from scratch; adjust at the edges.
- Dynamic windows live and die by the shrink step — get it right and the rest is bookkeeping.
Check your understanding
5 questions · first-try answers earn the most XP
My notes
Saved in this browser. Highlight a line above and save it, or write it in your own words.
Nothing saved yet. Your highlights will live here.
References
Finished reading?
Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.
Related chapters
Practice this pattern elsewhere
More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.
Spotted a mistake or want a topic covered? Report an issue