Sliding window (variable size)
medium 20 minA variable sliding window keeps a contiguous range [left, right] that grows on the right to explore and shrinks on the left whenever a validity rule breaks.
See it run
Grow the window on the right, shrink it on the left whenever the rule breaks, and watch every index enter once and leave once.
Operations
Longest without repeats (set)
Longest substring of "abcabcbb" with no repeated character. The set holds what is inside the window; a repeat makes the left edge crawl forward until the old copy is gone.
Step 1 of 11
Start: an empty window
s
- a0L
- b1
- c2
- a3
- b4
- c5
- b6
- b7
set
- ∅0
L sits at index 0, the set is empty and best = 0. R will visit every index once.
Step 1: Start: an empty window
def longest_unique(s): seen = set() left = 0 best = 0 for right in range(len(s)): while s[right] in seen: # repeat: shrink from the left seen.remove(s[left]) left += 1 seen.add(s[right]) # expand best = max(best, right - left + 1) return best- Time
- O(n)
- Space
- O(min(n, alphabet))
- brute force
- O(n²) with a running set
- moves here
- 8 right + 7 left
Use while, not if: a repeat can sit several places inside the window, and every character before it has to go.
In the real world
The same sliding window (variable size) doing real jobs. Pick one and step through it.
The step-by-step from the original lesson: start empty, expand three times, hit a repeat and shrink.
Step 1 of 5
Step 0: initialise
s
- a0LR
- b1
- c2
- a3
- b4
set
- ∅0
L and R both start at index 0 with an empty set and max = 0.
Step 1: Step 0: initialise
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Shrinking with if instead of while
criticalOne removal is not always enough. On "abcbd" the old b sits one place in from the left, so a and b must both go. With if, only a goes, the window "bcbd" keeps two b's and the answer comes out as 4 instead of 3.
Wrongfor right in range(len(s)): if s[right] in seen: # removes only one character seen.remove(s[left]) left += 1 seen.add(s[right])Rightfor right in range(len(s)): while s[right] in seen: # removes until the old copy is gone seen.remove(s[left]) left += 1 seen.add(s[right])Letting left jump backwards
criticalThe last-index map remembers characters that have already left the window. On "abba" the final a points at index 0, and jumping to 1 moves left back, giving 3 instead of 2.
Wrongif ch in last: left = last[ch] + 1 # may be smaller than leftRightif ch in last and last[ch] >= left: left = last[ch] + 1 # or: left = max(left, last[ch] + 1)Leaving zero counts in the map
majorWhen validity is len(counts) <= k, a key with count 0 still counts as a kind, so the window shrinks further than it needs to and the answer comes out too small.
Wrongcounts[out] -= 1left += 1 # counts may now hold {"r": 0}Rightcounts[out] -= 1if counts[out] == 0: del counts[out]left += 1Recording a shortest window after the loop
majorFor shortest problems the shrink loop runs while the window is good, and its last removal makes it bad. Measuring after the loop records an invalid window that is one too short.
Wrongwhile total >= target: total -= nums[left] left += 1best = min(best, right - left + 1) # this window is no longer goodRightwhile total >= target: best = min(best, right - left + 1) # record while still good total -= nums[left] left += 1Starting a minimum at 0 or returning infinity
minormin(0, length) is always 0, and when no window is ever good the function should return 0, not inf.
Wrongbest = 0...return best # always 0Rightbest = float("inf")...return 0 if best == float("inf") else bestUsing a sum window with negative numbers
criticalNegatives make the sum non-monotone. On [5, -10, 4, 3] with target 7 the window returns 0, but [4, 3] works. Use prefix sums instead.
Wrong# nums may contain negativesreturn min_subarray_len(7, [5, -10, 4, 3]) # 0, wrongRight# prefix sums: sum(l..r) = P[r + 1] - P[l]# exact k: hash map of prefixes; at least k: monotonic dequeprefix = [0]for x in nums: prefix.append(prefix[-1] + x)
Interview tips
How to explain it
- State the rule that makes a window valid, and why growing cannot fix a broken window.
- For each right: add s[right]; while invalid, remove s[left] and move left; record.
- Each index enters once and leaves at most once: at most 2n moves, O(n).
- Space is the state: a set or counts map, O(min(n, alphabet)), or O(1) for a sum.
Spot it in problems
- Longest or shortest substring or subarray under a rule.
- At most k distinct, at most k replacements, no repeats.
- Smallest window containing every character of another string.
- Sum at least a target, with non-negative numbers only.
Memory tricks
- EXPAND, SHRINK, UPDATE: an elastic band stretched by right and snapped back by left.
- Longest: shrink while broken, record after. Shortest: shrink while good, record inside.
- Examples to know cold: "abcabcbb" gives 3, [2, 3, 1, 2, 4, 3] with 7 gives 2, "ADOBECODEBANC" with "ABC" gives "BANC".
Watch out
- while, not if, when shrinking.
- left never moves back: guard last-index jumps.
- Delete zero counts; use == need when counting have.
- Negative numbers in a sum: prefix sums, not a window.