The problem it solves
There are two variants: fixed-size and variable-size. A fixed-size window slides one position at a time.
Fixed Windows: Add One, Remove One
To find the maximum sum of k consecutive elements, the naive approach sums each window from scratch. That takes k additions per position, or O(n · k) work in total.
But sliding from position i to i+1 only removes one element and adds one:
Two steps instead of k, no matter how large k is. Compare the step counters as you raise k. The sliding window's count does not move.
For [2, 1, 5, 1, 3] with a window of three, the first sum is 2 + 1 + 5 = 8. Slide one place: subtract 2 and add 1 to get 7. Slide again: subtract 1 and add 3 to get 9. The maximum window sum is 9; each move takes constant work, so the full scan is O(n).
Variable Windows: Grow and Shrink
Harder problems let the window change size. The pattern is always the same:
- Expand the right edge until the window meets (or violates) some condition.
- Contract the left edge while the condition still holds, recording the best answer.
Both pointers only ever move forward, so though the code holds nested loops, each element is added once and removed once. Total work is still O(n). That amortised argument is the part people find surprising.
How to Spot One
Reach for a sliding window when the problem asks about a contiguous subarray or substring, and phrases it as longest/shortest/maximum/minimum meeting a condition.
The critical requirement is that the running summary can be updated incrementally. Sums and counts work. If the condition needs the whole window recomputed. A median, say. You need a heavier structure such as a heap or balanced tree alongside the window.
Try it yourself: Sliding Window
- Run max-sum with k = 3. Watch each slide subtract one value and add one. Two steps, never three.
- Raise k to 5. The naive cost climbs while the sliding-window step count stays flat. That is the whole point.
Where it is used
- Rate limiting. Requests in the last 60 seconds is a sliding window over timestamps.
- Streaming statistics. Moving averages, rolling maxima, and any windowed aggregate over a data stream.
- Network protocols. TCP's sliding window controls how much unacknowledged data may be in flight.
- Time-series features. Rolling means and standard deviations for forecasting models.
- Text handling. Finding substrings with given character properties; n-gram extraction.
- Anomaly detection. Comparing a recent window against a baseline.
Rate limiting is a common production use. A sliding log or counter can enforce a quota over a rolling interval. A fixed-window counter is simpler, but can allow nearly twice the intended rate when requests fall on opposite sides of a window boundary.
Common mistakes with Sliding Window
- Shrinking in the wrong condition — the longest/shortest inversion described above.
- Recording the answer at the wrong point, before rather than after restoring validity.
- Not removing from the state when shrinking, so counts drift.
- Using it on non-contiguous problems. Sliding window is only for runs; subsequences need dynamic programming.
- Recomputing the aggregate from scratch, which discards the entire edge.
- Off-by-one in the window size: the width is
right - left + 1.