hardSliding WindowDequeSliding Window

Sliding Window Maximum

hardTime: O(n)Space: O(k)

Recognize the pattern

maximum in each sliding window of size kthe max must survive as the window slidestrack candidates efficiently

Brute force idea

If you approach Sliding Window Maximum in the most literal way possible, you get this: For each window position, scan all k elements for the max. Re-scans overlapping elements redundantly. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

The real unlock in Sliding Window Maximum comes when you notice this: Monotonic decreasing deque: maintain a deque of indices where values are in decreasing order. The front is always the current window's maximum. Remove from front when it falls out of the window; remove from back when a larger element arrives. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Sliding Window Maximum is this: The deque front is always the index of the maximum in the current window. The deque is decreasing — any element smaller than a newer element can never be a future maximum and is discarded. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

A common way to get lost in Sliding Window Maximum is this: reaching for a heap and then fighting stale elements that have already left the window. A monotonic deque works better because every index enters once, leaves once, and stays ordered by usefulness. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Sliding Window Pattern