Sliding window: fixed size
A window of exactly k neighbouring elements slides one step at a time. Each step adds the element coming in and removes the one going out, so every window costs O(1) instead of O(k).
How to recognise it
- The problem talks about every subarray or substring of a given length k.
- You need a sum, count, maximum or first-something for each block of k neighbours.
- The answer is a block of fixed width whose width you can work out first (for example, the number of good elements).
- Taking k items from the two ends of an array, which leaves one fixed-size block in the middle untouched.
The idea in one picture
Put a cardboard frame k cells wide on a row of numbers. To look at the next block, slide the frame one cell to the right: one number appears on the right edge and one disappears from the left edge. Everything else stays under the frame. So keep a running summary of what is under the frame, and on each slide apply only the two changes. That turns O(n·k) work into O(n).
Template: something for every window of size k
summary = empty
for right from 0 to n - 1:
add nums[right] to summary # element entering
if right >= k:
remove nums[right - k] from summary # element leaving
if right >= k - 1:
record the answer for the window right - k + 1 .. right
The summary can be a sum, a count of "bad" elements, a frequency table, or a queue of useful indexes. The template does not change, only what "add" and "remove" mean.
A guided example: largest sum of 3 neighbours in [2, 1, 5, 1, 3, 2]
| right | entering | leaving | window | sum | best |
|---|---|---|---|---|---|
| 2 | 5 | none | [2, 1, 5] | 8 | 8 |
| 3 | 1 | 2 | [1, 5, 1] | 7 | 8 |
| 4 | 3 | 1 | [5, 1, 3] | 9 | 9 |
| 5 | 2 | 5 | [1, 3, 2] | 6 | 9 |
When the width is hidden
Some problems do not say k, but the answer must be a block of a width you can compute. "Bring every value at most k together" needs a block exactly as wide as the number of such values. "Choose m packets with the smallest spread" becomes a window of m once the array is sorted. "Take k cards from the ends" leaves a middle block of n - k. Spot the hidden width, and the problem is a fixed window again.
Common mistakes
- Removing
nums[right - k + 1]instead ofnums[right - k], an off-by-one that keeps the window one too small. - Recording an answer before the first window is full.
- Rebuilding the summary from scratch for every window, which brings back the O(n·k) cost.
- For a maximum or minimum, a plain running value cannot "remove" the leaving element. That needs a monotonic deque, which comes later in the stack and queue area.
Problems
- Maximum Points You Can Obtain from Cardsmediumguide ready
- Chocolate Distribution problemmediumguide ready
- Minimum swaps required bring elements less equal K togethermediumguide ready
- First negative integer in every window of size “k”mediumguide ready