Sliding Window
Maintain a window over a contiguous range and update it incrementally, solving longest/shortest subarray and substring problems in O(n).
Intermediate · about 6 hours · difficulty 3/5
Learn first: Two Pointers, Hash Tables and Hashing Patterns
Sliding window is two pointers specialised for contiguous subarrays or substrings. Instead of recomputing each window from scratch, you add the element entering on the right and remove the one leaving on the left.
Fixed-size window
For "max sum of any k consecutive elements", compute the first window, then slide: add a[i], subtract a[i - k]. O(n) instead of O(nk).
Variable-size window
The general template:
- Expand
rone step at a time, addinga[r]to the window state (a sum, a count map, a set). - While the window is invalid, shrink from the left by removing
a[l]and incrementing l. - Record the answer (longest valid window) after shrinking, or record the shortest while the window is still valid.
This solves Longest Substring Without Repeating Characters, Minimum Window Substring, Longest Repeating Character Replacement and "at most k distinct" problems.
When it works
The window condition must be monotonic: if a window is invalid, every larger window containing it is also invalid. With negative numbers, "sum >= target" is not monotonic and you need prefix sums or a deque instead.
Tricks
"Exactly k" is often computed as atMost(k) - atMost(k - 1). For window maximums, combine the window with a monotonic deque (covered later).
Key concepts
- Fixed-size window
- Variable window expand/shrink template
- Window state with count maps
- Monotonic validity condition
- Exactly k = atMost(k) - atMost(k-1)
- When windows fail (negative numbers)
Mini project
Solve 8 problems: Maximum Average Subarray I, Longest Substring Without Repeating Characters, Longest Repeating Character Replacement, Permutation in String, Minimum Size Subarray Sum, Minimum Window Substring, Fruit Into Baskets, and Subarrays with K Different Integers.
Check yourself
Why does the variable sliding window fail for 'shortest subarray with sum at least k' when the array contains negative numbers?
Free resources
- NeetCode Roadmap (Sliding Window) (NeetCode)
- Window sliding technique (GeeksforGeeks)
- LeetCode Problem Set (LeetCode)