Sliding Window
Transform O(n²) subarray brute force into O(n) elegance. One pointer expands, one pointer shrinks — the window does the work.
Max subarray sum — n² inner loops vs one pass
The insight: two adjacent windows of size k share k−1 elements. Instead of re-summing from scratch, subtract the element leaving the left edge and add the element entering the right edge. O(1) per slide.
The Two Window Types
Every sliding window problem uses one of these. Identify which before coding.
Window size k is given. Slide one step at a time: add right element, remove left element. Window size never changes.
Window expands and shrinks based on a condition. Expand right while valid, shrink left when violated. Size changes dynamically.
The 3-Step Sliding Window Framework
The thinking process every sliding window expert uses. Internalize it.
Set up left = 0, right = 0, and any tracking data structures (sum, set, hashmap, frequency counter). For fixed windows, build the initial window of size k first.
left = 0; window_sum = sum(nums[:k]); max_sum = window_sum
Advance the right pointer one step at a time. Add the new element to your window state. For fixed windows this happens every iteration. For variable, always expand first.
window_sum += nums[right] # or char_set.add(s[right])
For fixed windows: always remove nums[right - k]. For variable windows: shrink left while the window condition is violated. Update window state as you remove.
while condition_violated:
remove s[left]; left += 1Pattern Recognition
30-second diagnosis: is this sliding window?