DSA Master › Topic 3
Sliding Window
A window [l, r] moves across a string or array. Expand r to take in elements, and shrink l when the window breaks a constraint. Each element enters and leaves once, so the whole pass is O(n).
Concepts
- Fixed window
- Variable window
- Frequency window
- Monotonic deque
How to recognise it
- The problem asks for the longest, shortest or count of a contiguous subarray or substring.
- There's a constraint like "at most k distinct", "no repeats" or "sum ≤ k".
- The window size is fixed (k) and you need a value for every window.
Common pitfalls
- Sliding windows need monotonic validity. With negative numbers, use prefix sums instead.
- For "minimum window" problems, record the answer inside the shrink loop.
Problems
- Maximum Average Subarray I (Easy)
- Longest Substring Without Repeating Characters (Medium)
- Longest Repeating Character Replacement (Medium)
- Permutation in String (Medium)
- Find All Anagrams in a String (Medium)
- Minimum Window Substring (Hard)
- Sliding Window Maximum (Hard)
- Max Consecutive Ones III (Medium)
- Fruit Into Baskets (Medium)
- Subarray Product Less Than K (Medium)