Sliding Window Maximum
Core idea: As a window slides, a smaller value sitting behind a larger, newer one can never be the max again โ so throw it away the moment it's beaten. Keep a deque of indices whose values strictly decrease; the front is always the window's maximum, and every element enters and leaves at most once โ O(n).
1. The problem, in a fresh setting
You run autoscaling for a service. Every second you record a latency sample. To decide whether to scale, you need the peak latency over the last k seconds, recomputed each second as the window slides forward. Spikes must surface instantly; stale samples must drop out the back.
Given a stream nums and window size k, output the maximum of every length-k window, left to right.
nums |
k |
Output |
|---|---|---|
[4, 1, 5, 2, 6, 2, 3] |
3 |
[5, 5, 6, 6, 6] |
[9, 11] |
1 |
[9, 11] |
[8, 3, 5] |
3 |
[8] |
For the first row there are 7 - 3 + 1 = 5 windows; each output is that window's max.
Sign in to continue reading
The rest of this lesson is available with a free account. Signing in with Google or Microsoft is free.
Sign in to read the full lesson