Sliding Window — the pattern for subarray problems
Sliding Window — a moving frame over the array
You look at a contiguous slice of the array or string. As you move to the right, you add the new element and subtract (or shrink until you can drop) the leftmost element. Turns many O(n·k) or O(n²) problems into O(n).
Two flavors
Fixed-size window
The window is always exactly k wide. Slide it right by 1. Update the aggregate incrementally.
- Max sum of k consecutive elements
- Average of every window of size k
- Number of window-of-size-k anagrams
Variable-size window
Grow the window until a condition breaks. Shrink from the left until it's valid again.
- Longest substring with unique characters
- Smallest subarray with sum ≥ target
- Longest substring with at most k distinct characters
The shape
lo = 0
for hi, x in enumerate(seq):
# add x to the window
while <window is invalid>:
# remove seq[lo]
lo += 1
# window from lo..hi is valid — record answer
Common pitfalls
- Forgetting to update the answer inside the loop. Track the best while you go.
- Off-by-one on window length.
hi - lo + 1is the length whenhiandloare inclusive indices. - Assuming the window can only grow. Some variants (min-sum with negatives) need both grow AND shrink.
Try it
- Write
min_subarray_len(target, nums)— smallest window whose sum is ≥ target. - Write
longest_at_most_k_distinct(s, k)— longest substring with at most k distinct characters.
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
- Exercise 1
Given
nums = [2, 1, 5, 1, 3, 2]andk = 3, find max sum of any 3 consecutive elements using a sliding window. Print — expected 9. - Exercise 2
Given
nums = [1, 4, 2, 10, 2, 3, 1, 0, 20]andk = 4, find max sum of any 4 consecutive elements using a sliding window. Expected: 24. - Exercise 3
Given
s = 'abcabcbb', find length of longest substring with all-unique characters. Variable-size sliding window + dict of last-seen indices. Expected: 3.