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.
Video lesson · Chapter 1 of 7
The wristband scanner
Longest window
1:19Reel
More reels
One idea each, a minute or less.
Shortest window
1:18Reel
Window with a frequency map
1:16Reel
Minimum window substring
1:15Reel
Exactly K
1:16Reel
How it works
Step through the idea, or press Play.
Grow right. Add s[right] to the window state: a set, a counts map or a running sum
Understand it
Start here
Recap: a window that changes size
Fixed window
Width never changes: add one value on the right, drop one on the left. See Sliding window (fixed size).
Two pointers
Two indexes that only move forward. The variable window is the reader/writer shape with a state between them. See Two pointers.
Hash maps and sets
The window's state is usually a set of what is inside or a map of counts, each update . See Hash usage.
In a variable window nobody tells you the width. The problem gives a rule instead, such as "no repeated characters" or "sum at least 7", and asks for the longest or shortest contiguous range that obeys it. Classic example: the longest substring of "abcabcbb" without repeating characters is "abc", length 3.
The template
Grow right, shrink left, then record
right walks every index once in a for loop and adds s[right] to the state. If that broke the rule, a while loop removes s[left] and moves left up until the window is valid again. Then the window [left, right] is the best window that ends at right, so compare its length, , with the best so far.
One turn of the loop
left never moves back.def longest_valid(items): state = make_state() # set, counts map, running sum... left = 0 best = 0 for right in range(len(items)): add(state, items[right]) # 1. EXPAND while not valid(state): remove(state, items[left]) # 2. SHRINK left += 1 best = max(best, right - left + 1) # 3. UPDATE (window is valid) return bestadd, remove and valid change between problems.- 1EXPANDright++, add the new item
- 2SHRINKwhile invalid: remove s[left], left++
- 3UPDATEtrack the best valid window
Why it is safe
The validity condition must be monotone
The template throws away every window that starts before the new left. That is only safe if a window that is invalid cannot become valid by growing on the right. For "at most" rules this holds: adding a character never removes a repeat, and adding a non-negative number never lowers a sum.
Monotone validity
left is pushed past no window starting at is ever needed again.What the state is and when the window is valid
| Problem | State | Valid when | Record |
|---|---|---|---|
| Longest substring without repeats | set (or last-index map) | s[right] not already inside | longest, after shrinking |
| Longest with at most k distinct | counts map | len(counts) <= k | longest, after shrinking |
| Minimum size subarray sum | running total | total >= target is the goal | shortest, inside the loop |
| Minimum window substring | window counts, have | have == required is the goal | shortest, inside the loop |
Example 1
Longest substring without repeating characters
State: a set of the characters inside the window. When s[right] is already in the set, the window would hold a repeat, so remove characters from the left until the old copy is gone, then add s[right]. On "abcabcbb" the window grows to abc, then slides as bca, cab, abc, and shrinks to cb and b at the end. Best: 3.
Trace on "abcab"
| right | char | Action | left | Window | Set | best |
|---|---|---|---|---|---|---|
| 0 | a | add | 0 | a | {a} | 1 |
| 1 | b | add | 0 | ab | {a, b} | 2 |
| 2 | c | add | 0 | abc | {a, b, c} | 3 |
| 3 | a | repeat: drop a, then add | 1 | bca | {b, c, a} | 3 |
| 4 | b | repeat: drop b, then add | 2 | cab | {c, a, b} | 3 |
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 bestfor s in ["abcabcbb", "bbbbb", "abcdef", "pwwkew", "aab", ""]: print(repr(s), longest_unique(s)) # 3 1 6 3 2 0What happens to one new character
"abba" the second b removes a and then b: left jumps from 0 to 2.Example 1, faster
Last-index map: jump left instead of crawling
Instead of a set, store where each character was last seen. When s[right] was seen at index inside the window (), the window must start after it, so set left = j + 1 in one jump. Same bound, but each step does work instead of a crawl.
def longest_unique(s): last = {} # char -> index where it was last seen left = 0 best = 0 for right, ch in enumerate(s): if ch in last and last[ch] >= left: left = last[ch] + 1 # jump past the old copy last[ch] = right best = max(best, right - left + 1) return bestprint(longest_unique("abba")) # 2print(longest_unique("tmmzuxt")) # 5 ("mzuxt")>= left check is the whole trick.| Version | How left moves | Time | Space | Watch for |
|---|---|---|---|---|
| Set | crawls one step at a time | amortised | use while, not if | |
| Last-index map | jumps to last[ch] + 1 | , no inner loop | stale entries: check >= left |
Example 2
Minimum size subarray sum: the shortest valid window
Given positive numbers and a target, find the shortest contiguous subarray whose sum is at least target. Now validity is the goal, not the constraint: grow until total >= target, then shrink as far as possible while it stays true, recording the length before each removal. On [2, 3, 1, 2, 4, 3] with target 7 the lengths found are 4, 4, 3, 3 and finally 2 for [4, 3].
Where to record: longest versus shortest
def min_subarray_len(target, nums): left = 0 total = 0 best = float("inf") for right in range(len(nums)): total += nums[right] # expand while total >= target: # still good: try smaller best = min(best, right - left + 1) total -= nums[left] left += 1 return 0 if best == float("inf") else bestprint(min_subarray_len(7, [2, 3, 1, 2, 4, 3])) # 2print(min_subarray_len(4, [1, 4, 4])) # 1print(min_subarray_len(11, [1, 1, 1, 1])) # 0Example 3
Longest substring with at most k distinct characters
State: a counts map of the characters inside. The window is valid while len(counts) <= k. When a new character makes it , crawl left forward, decrementing counts, and delete a key when its count hits 0 so that len(counts) stays honest. On "araaci" with the best is "araa", length 4; on "eceba" it is "ece", length 3.
def longest_k_distinct(s, k): counts = {} left = 0 best = 0 for right, ch in enumerate(s): counts[ch] = counts.get(ch, 0) + 1 while len(counts) > k: # too many kinds: shrink out = s[left] counts[out] -= 1 if counts[out] == 0: del counts[out] # keep len(counts) honest left += 1 best = max(best, right - left + 1) return bestprint(longest_k_distinct("araaci", 2)) # 4print(longest_k_distinct("eceba", 2)) # 3print(longest_k_distinct("aa", 0)) # 0Trace on "araaci", k = 2
| right | char | counts after shrink | left | Window | best |
|---|---|---|---|---|---|
| 0 | a | {a: 1} | 0 | a | 1 |
| 1 | r | {a: 1, r: 1} | 0 | ar | 2 |
| 2 | a | {a: 2, r: 1} | 0 | ara | 3 |
| 3 | a | {a: 3, r: 1} | 0 | araa | 4 |
| 4 | c | {a: 2, c: 1} | 2 | aac | 4 |
| 5 | i | {c: 1, i: 1} | 4 | ci | 4 |
c, three kinds: drop a (count 2), then r (count 0, deleted). At i, drop two more as.Example 4
Minimum window substring: need and have
Find the shortest substring of s that contains every character of t, with multiplicity. need counts t. window counts the current range. have is how many distinct characters already meet their need, and the window is good when have == required, where required = len(need). On s = "ADBECFEBAC", t = "ABC" the windows found are ADBEC (5), EBAC (4) and finally `BAC` (3).
Keeping have in step with the counts
have changes only when a count crosses its need, so checking validity is instead of comparing two maps.from collections import Counterdef min_window(s, t): if not t: return "" need = Counter(t) required = len(need) # distinct characters to satisfy have = 0 # how many are satisfied now window = {} left = 0 best_len, best_left = float("inf"), 0 for right, ch in enumerate(s): window[ch] = window.get(ch, 0) + 1 if ch in need and window[ch] == need[ch]: have += 1 while have == required: # good: squeeze it if right - left + 1 < best_len: best_len, best_left = right - left + 1, left out = s[left] window[out] -= 1 if out in need and window[out] < need[out]: have -= 1 left += 1 return "" if best_len == float("inf") else s[best_left:best_left + best_len]print(min_window("ADBECFEBAC", "ABC")) # BACprint(min_window("ADOBECODEBANC", "ABC")) # BANCprint(min_window("a", "aa")) # (empty)Complexity
Why it is O(n): each index enters once and leaves once
The while inside the for looks like , but count pointer moves instead of loop nesting. right moves times. left starts at 0, only increases, and never passes , so across the whole run it moves at most times. Each move does work on a set, a map or a sum.
Amortised count
left travels, at most .Against brute force
"abcabcbb" () brute force looks at 36 substrings; the window makes 8 right moves and 7 left moves, 15 in total. Space is the state: for a set or map, for a sum.Limits
When it fails: negative numbers need prefix sums
With negatives the sum is no longer monotone: growing can lower it and shrinking can raise it. Take [5, -10, 4, 3] with target 7. The running sums are 5, −5, −1, 2, never 7 or more, so the window never shrinks and returns 0, yet [4, 3] sums to exactly 7. The −10 is stuck inside, and nothing in the rule says to drop it.
Window or prefix sums?
The prefix-sum rewrite
def count_sum_k(nums, k): seen = {0: 1} # prefix sum -> how many times seen prefix = 0 count = 0 for x in nums: prefix += x count += seen.get(prefix - k, 0) seen[prefix] = seen.get(prefix, 0) + 1 return countprint(count_sum_k([5, -10, 4, 3], 7)) # 1 ([4, 3])print(count_sum_k([1, -1, 1, -1], 0)) # 4Patterns
The family of variable-window problems
| Problem | Type | State | Notes |
|---|---|---|---|
| Longest substring without repeats | longest | set or last index | The first one to learn |
| Longest with at most k distinct | longest | counts map | Fruit Into Baskets is k = 2 |
| Longest repeating character replacement | longest | counts + max count | Valid while length - maxCount <= k |
| Max consecutive ones with k flips | longest | count of zeros | Valid while zeros <= k |
| Minimum size subarray sum | shortest | running sum | Positive numbers only |
| Minimum window substring | shortest | need, window, have | Record inside the loop |
| Subarrays with product below k | count | running product | Add right - left + 1 per step |
right, which is right - left + 1.Do
- Write the validity rule in words before coding.
- Use a
whileto shrink, not anif: one removal may not be enough. - Delete map keys whose count reaches 0 when you use
len(counts). - Record longest after shrinking; record shortest inside the shrink loop.
- Check the signs: negatives in a sum mean prefix sums.
Don't
- Recompute the window's set or sum from scratch on each step.
- Let
leftmove backwards (stale last-index entries). - Use the window for subsequences: it only handles contiguous ranges.
- Return infinity, or start a minimum at 0.
- Forget the empty input and the case where no window is ever valid.
Recap
Key takeaways
Key points
- A variable window grows on the right and shrinks on the left to keep a validity rule.
- It works when the rule is monotone: a broken window cannot be fixed by growing.
- Template: for right, add; while invalid, remove s[left] and left += 1; record.
- Longest: record after shrinking. Shortest: record inside the shrink loop before each removal.
- State is a set, a last-index map, a counts map or a running sum, all O(1) per update.
- Minimum window substring tracks need, window counts and have == required.
- Each index enters once and leaves at most once: at most 2n moves, O(n) amortised.
- Negatives break sum windows: switch to prefix sums with a hash map or a monotonic deque.