Sliding Window Maximum – Solution & Complexity
1. Understanding the Problem
- A window of
kconsecutive elements slides one step at a time acrossnums. - For each position of the window we report its maximum.
- A length
narray with windowkyieldsn - k + 1answers.
2. Why Naive Is Too Slow
- Recomputing the max of every window from scratch is
O(n * k). - For large inputs that is too slow, so we want each element processed a constant number of times.
- The trick: maintain a structure that gives the current window's max in
O(1).
3. A Monotonic Deque of Indices
- Store indices in a deque whose corresponding values are decreasing.
- Before adding a new index, pop smaller values from the back: they can never be the max while the newcomer is around.
- The front of the deque is therefore always the index of the current window's maximum.
4. Evicting Indices That Left the Window
- The front index is stale once it falls outside
[i - k + 1, i]. - Pop it from the front when
dq[0] <= i - k. - Once we have seen at least
kelements (i >= k - 1), recordnums[dq[0]].
5. Complexity
- Time:
O(n)since every index is added and removed from the deque at most once. - Space:
O(k)for the deque plusO(n)for the output.