Pattern Overview: The Sliding Window Technique
The Sliding Window pattern is one of the most powerful techniques for solving contiguous subarray and substring problems. Instead of recalculating everything from scratch for each position, you maintain a "window" that slides through the data, efficiently updating state by adding elements on one side and removing them from the other.
Two Types of Sliding Window:
- •
Fixed Size Window: Window size k stays constant. Add right element, process window, remove left element.
- •
Variable Size Window: Window expands and contracts based on constraints. Expand right freely, shrink left when constraint violated.
The Key Insight: Both types run in O(n) because each element is added at most once and removed at most once.
When to Use Sliding Window:
- •Problems mentioning "contiguous subarray" or "substring"
- •Finding longest/shortest subarray with a constraint
- •Maximum/minimum sum of k consecutive elements
- •Anagram or permutation finding
- •Character replacement within a limit