Sliding Window
Overview
A sliding window is a pair of indices [left, right] that defines a contiguous range. At each step, you expand (move right) or contract (move left) to maintain an invariant, distinct characters, bounded frequency, sum ≤ target, etc. Each element enters and leaves the window at most once, so total work is O(n) even though the window size varies.
There are two flavors:
- Variable-size window, common for “longest/shortest substring satisfying X.” Expand
right; when the invariant breaks, contractleftuntil it holds again. - Fixed-size window, common for “max/min over every window of size k.” Slide
rightforward by one andleftforward by one in lockstep.
Problems
- 121. Best Time to Buy and Sell Stock (Easy)
- 3. Longest Substring Without Repeating Characters (Medium)
- 424. Longest Repeating Character Replacement (Medium)
- 567. Permutation in String (Medium)
- 76. Minimum Window Substring (Hard)
- 239. Sliding Window Maximum (Hard)
Key patterns unlocked here
- Running best + single pass, Buy/Sell Stock; the “one-pass min-tracking” template.
- Hash set / map as window state, Longest Substring Without Repeating.
- Window + frequency count with max-freq invariant, Longest Repeating Character Replacement.
- Anagram detection with matching counters, Permutation in String.
- Two-counter tracking (have vs. need), Minimum Window Substring.
- Monotonic deque for window min/max, Sliding Window Maximum.