Sliding Window
Slide a range across the data, updating its answer by adding one element and removing one, instead of recomputing it from scratch.
After this lesson you will be able to
- Explain why recomputing each contiguous range from scratch wastes work, and how a window reuses it.
- Solve fixed-size window problems (best sum of k items) in O(n).
- Solve variable-size window problems with the expand-then-shrink pattern.
- Explain why the variable window needs a property that only moves one way (for example, non-negative numbers).
- Track window contents with a dictionary to handle “at most k distinct” style conditions.
Before you start. Two Pointers first: a window is two pointers that bound a contiguous range. Prefix Sums are helpful for comparison.