← back to stream

Sliding window

Sliding window is the technique of maintaining a "window" over a contiguous range of an array or string and updating it incrementally as it slides, rather than recomputing from scratch. It collapses O(n × k) nested-loop patterns into O(n) — when you move the window by one, you add the new element entering and subtract the old one leaving, instead of re-summing the whole window. Typical cues: "longest substring with property X", "max/min/average over any window of size k", "smallest range covering all tokens". Variable-size variants grow and shrink the window based on a condition. Rate limiters (100 requests per minute) are a production example — you maintain a sliding time window and count requests inside it. Once you see the pattern, half the "hard" array problems become easy.