Sliding Window Maximum

hard

Given an array nums and a window size k, the window slides from the left to the right of the array, one position at a time, always covering k consecutive elements. Return an array of the maximum in each window position.

Hints

Recomputing each window's max is O(n*k) — reuse work as the window slides.
Keep a deque of indices whose values decrease, so the front is always the max.
Evict the front when it leaves the window and the back when it's dominated by a new element.

Common doubts

You need to detect when the maximum has slid out of the window, which requires knowing its position — the index.
Once a larger, more recent element arrives, any smaller earlier element can never be the maximum of a future window, so it's dead weight.
Each index is appended once and removed once across the entire scan, so total deque work is linear.

Interview follow-ups

Keep an increasing deque instead, popping back indices whose values are >= the new element.
Yes — a min/max queue built from two stacks (each augmented like a Min Stack) gives the same amortized O(1) window extreme.

Fun facts

  • The monotonic deque is the sliding-window upgrade of the monotonic stack — it's the standard tool for window extrema.
  • This exact structure computes running maxima in image processing (morphological dilation) in linear time.

Asked at

AmazonGoogleMetaMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]
The maximum of each size-3 window as it slides across the array.
Example 2
Input: nums = [1], k = 1
Output: [1]
A single window containing 1.
Constraints

- 1 <= nums.length <= 10^5 - -10^4 <= nums[i] <= 10^4 - 1 <= k <= nums.length

Solve this problem →