Sliding Window Maximum

Difficulty: Hard

You're given a list of numbers and a window size k. A window of size k starts at the beginning and slides right one step at a time to the end.

Return the maximum value in each window position, in order.

Examples

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

The first window [1,3,-1] has max 3, the next [3,-1,-3] has max 3, then [-1,-3,5] has max 5, and so on.

Input: nums = [1], k = 1
Output: [1]

Only one window, containing the single element.

Input: nums = [9, 11], k = 2
Output: [11]

Only one window fits (size 2 over a list of length 2), and its maximum is 11.

Constraints

  • 1 <= nums.length <= 10^5

  • -10^4 <= nums[i] <= 10^4

  • 1 <= k <= nums.length

Approach

The direct approach scans all k elements of every window for the max. It's correct, but each element is compared again in every window it's part of.

The key insight: if an older number is smaller than a newer one in the window, it can never be the max of a future window. The newer, larger number stays in the window at least as long. So the older one can be dropped.

Keep a deque (a list you can add to or remove from at both ends) of indices, with values decreasing from front to back:

  • When a new number arrives, pop indices from the back whose values are smaller, then add the new index.
  • Remove the front index if it has slid out of the window.
  • The front now holds the current window's max.

Each index is added and removed at most once, so it's a single pass.

Solutions

Brute Force — Scan Every Window

For each window, check all k elements to find the maximum.

function maxSlidingWindow(nums, k) {
  const result = [];

  for (let start = 0; start + k <= nums.length; start++) {
    let windowMax = -Infinity;
    for (let i = start; i < start + k; i++) {
      windowMax = Math.max(windowMax, nums[i]);
    }
    result.push(windowMax);
  }

  return result;
}

Time: O(n * k) · Space: O(1) extra, aside from the output list

Optimal — Monotonic Decreasing Deque

Keep a deque of indices with values decreasing from front to back, so the front is the window's max. Drop smaller values from the back before adding a new one, and drop the front once it leaves the window.

function maxSlidingWindow(nums, k) {
  const deque = []; // stores indices, values decreasing front to back
  const result = [];

  for (let i = 0; i < nums.length; i++) {
    // Remove indices from the back whose values can't beat the new number
    while (deque.length > 0 && nums[deque[deque.length - 1]] < nums[i]) {
      deque.pop();
    }
    deque.push(i);

    // Remove the front index if it has fallen out of the window
    if (deque[0] <= i - k) {
      deque.shift();
    }

    // Once the first full window is formed, record its maximum
    if (i >= k - 1) {
      result.push(nums[deque[0]]);
    }
  }

  return result;
}

Time: O(n) — each index is pushed and popped from the deque at most once · Space: O(k) for the deque