Sliding window
A sliding window maintains a contiguous slice of a sequence as the slice moves, adding on one side and dropping on the other. It turns many O(n²) subarray problems into O(n).
Detailed Explanation
The naive way to study every subarray is two nested loops over start and end. If the property you care about can be updated incrementally — a sum, a count of unique characters, a max in a deque — you can keep one window and slide it.
A fixed window of width k adds a[i] and removes a[i - k] as i advances. A running sum of length k is the textbook case. A variable window grows the right end until the constraint breaks, then advances the left end until it holds again. "Shortest substring that covers these characters" is that shape.
The state you store must be reversible, or cheap to recompute when the left end moves. A sum is reversible: subtract the leaving value. A set of counts is reversible: decrement. A max is not reversible with a single variable; you need a deque of candidates (collections.deque) that drops indices that are out of window or smaller than the new value.
deque(maxlen=k) is a sliding window of the last k items when you only need the items, not a derived aggregate. For aggregates, keep the window bounds as integers and the aggregate in extra variables.
Windows are contiguous. If the problem allows dropping elements from the middle, it is not a window problem. Subsequences are not subarrays.
Python slices (a[left:right]) copy. In a hot loop, do not slice each step. Index a[right] and a[left] and update the aggregate.
Code Examples
def max_sum_window(nums: list[int], k: int) -> int:
if k > len(nums) or k <= 0:
raise ValueError("bad k")
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k]
if window > best:
best = window
return best
print(max_sum_window([2, 1, 5, 1, 3, 2], 3)) # 9 (5+1+3)def longest_unique(s: str) -> int:
last = {}
left = 0
best = 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
print(longest_unique("abba")) # 2Common Gotchas
Slicing the window each iteration
`a[left:right]` is O(k). The whole algorithm becomes O(nk).
A max or min with only one variable
removing the current max has no replacement. Use a deque of indices.
Off-by-one on inclusive ends
`right - left + 1` is the length of an inclusive window. Draw an example of length 1.
Variable windows need a clear invariant
"the window is always valid" or "the window is the smallest invalid". Pick one and stick to it.