Sliding Window
The idea
For problems about contiguous subarrays or substrings, keep a "window" [left, right] and update its state as it moves, instead of recalculating from scratch.
Fixed-size window
"Max sum of k consecutive items": add the item entering, subtract the item leaving.
window = sum(a[:k])
for i in range(k, len(a)):
window += a[i] - a[i - k]
Variable-size window
"Longest substring without repeating characters", "smallest subarray with sum ≥ target":
- Expand
rightone step at a time and add the new item to the window state. - While the window breaks the rule, shrink from
left. - Record the best answer.
Each index enters and leaves the window at most once, so it's O(n).
Window state is usually…
- a running sum,
- a Counter or dict of character counts,
- a set of items in the window,
- a deque, for the max or min (Unit 5).
Recognise it
Keywords: "subarray", "substring", "consecutive", "contiguous", "longest or shortest… such that…".
| Pattern | Window |
|---|---|
| max or average of k items | fixed |
| longest with at most K distinct | variable |
| minimum window containing all of T | variable + counts |
| anagram of P in S | fixed (size of P) + counts |
Example
from collections import Counter
def max_sum_k(nums, k):
window = best = sum(nums[:k])
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
best = max(best, window)
return best
def longest_unique(s):
last, left, best = {}, 0, 0
for right, ch in enumerate(s):
if ch in last and last[ch] >= left:
left = last[ch] + 1
last[ch] = right
best = max(best, right - left + 1)
return best
def min_subarray_len(target, nums):
left, total, best = 0, 0, float("inf")
for right, x in enumerate(nums):
total += x
while total >= target:
best = min(best, right - left + 1)
total -= nums[left]
left += 1
return 0 if best == float("inf") else best
def find_anagrams(s, p):
need, window, out = Counter(p), Counter(s[:len(p)]), []
if window == need: out.append(0)
for i in range(len(p), len(s)):
window[s[i]] += 1
window[s[i - len(p)]] -= 1
if window == need: out.append(i - len(p) + 1)
return out
print(max_sum_k([2, 1, 5, 1, 3, 2], 3)) # 9
print(longest_unique("abcabcbb")) # 3
print(min_subarray_len(7, [2, 3, 1, 2, 4, 3])) # 2
print(find_anagrams("cbaebabacd", "abc")) # [0, 6]