How to recognise
a contiguous subarray or substring, the longest or shortest one that meets a condition.
How to solve problems like this
- Name the rule a good window follows: no repeats, sum at most k, at most k distinct letters.
- Choose what to keep about the window so the rule is quick to check: a set, a map of counts, a running sum.
- Grow the window on the right. While it breaks the rule, shrink it from the left.
- Update the answer while the window is good: after shrinking for the longest, while shrinking for the shortest.
Variant: Fixed size
The same, but the window keeps its size: each step one item comes in and one leaves. The answer for the window is adjusted from the last one, not counted again.
- Check that the window has a fixed length k: k numbers in a row, a substring as long as the pattern.
- Choose what to keep about the window so that one item in or out updates it in O(1): a running sum, a map of letter counts.
- Build the first window from the first k items and record the answer for it.
- Slide: add the item at right, remove the one at right - k, then update the answer. The same works for averages and for anagram windows with letter counts.
Where it's used
- TCP. A sender may send several packets without waiting for replies, but no more than the window allows. When a confirmation arrives, the window slides forward and the next packets can go.
- gzip and zip. Their compression, DEFLATE, looks for repeats in the last 32 KB of the text. The window moves along with the text, and a repeat is replaced by a short reference back into it.
- Rate limits. The rule "no more than 100 requests in the last minute" is a one-minute window that moves with the clock. Cloudflare counts its rate limits this way.