Skip to problem
←

Sliding Window Maximum

Hard 0 attempts

Given an integer array nums and a window size k, return the maximum of every contiguous window of exactly k elements.

Move the window one position to the right each time. Return the maxima in window order, producing exactly nums.length - k + 1 values. Equal values count normally, and all values may be negative.

For nums = [4,1,3,2] and k = 2:

Window Maximum
[4, 1] 4
[1, 3] 3
[3, 2] 3

The result is [4,3,3].

Function contract

Implement maxSlidingWindow(nums, k).

Output: Return an array of nums.length - k + 1 maxima in left-to-right window order.

Example 1

Input
nums = [1,3,-1,-3,5,3,6,7]
k = 3
Output
[3,3,5,5,6,7]

Example 2

Input
nums = [4,3,2]
k = 1
Output
[4,3,2]
Constraints
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length

Monotonic Deque

Keep indices in decreasing value order. Remove expired indices from the front and smaller values from the back. A head index avoids shifting an array on every removal; periodic compaction keeps storage proportional to the window size.

javascript
function maxSlidingWindow(nums, k) {
  const deque = [], result = []; let head = 0;
  for (let i = 0; i < nums.length; i++) {
    while (head < deque.length && deque[head] <= i - k) head++;
    while (deque.length > head && nums[deque[deque.length-1]] <= nums[i]) deque.pop();
    deque.push(i);
    if (i >= k - 1) result.push(nums[deque[head]]);
    if (head >= k) { deque.splice(0,head); head = 0; }
  }
  return result;
}

Time: O(n) amortized | Space: O(k) auxiliary space, excluding output

Loading discussion…

Saved in this browser only. Private to you.

JavaScript