Sliding Window Maximum

HardMonotonic Queue · Sliding Window🧩 Queue & Monotonic DequeLeetCode #239 ↗Updated

Problem

A window of fixed size k slides over the integer array nums from left to right, one position per step. Return an array holding the maximum value inside the window at each of its n - k + 1 positions.
Input[1,3,-1,-3,5,3,6,7], k=3Output[3,3,5,5,6,7]
Input[1], k=1Output[1]

1 ≤ n ≤ 105  ·  -104 ≤ nums[i] ≤ 104  ·  1 ≤ k ≤ n

Try it yourself

Java
class Solution {
    public int[] maxSlidingWindow(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
An element that has a larger element to its right inside the window can never be a maximum again. Throw such elements away; what remains is a decreasing deque whose front is always the window maximum.
PatternQueue & Monotonic Deque

Instinct Arrival order matters, or you need the max/min of a moving window - reach for a FIFO queue, or a deque of indices kept in sorted order.

Memory hack Old ones leave by the front door, weak ones get bounced out the back - so whoever stands at the front is always the champion.

Open the Queue & Monotonic Deque guide →

Approaches

Brute ForceRescan Every Window

Time O(n · k)Space O(1) extra

For each start i, scan nums[i..i+k-1] and record the maximum. Consecutive windows share k-1 elements, yet we recompute everything from scratch.

Java
public int[] maxSlidingWindow(int[] nums, int k) {
    int[] result = new int[nums.length - k + 1];
    for (int i = 0; i <= nums.length - k; i++) {
        int max = Integer.MIN_VALUE;
        for (int j = i; j < i + k; j++) max = Math.max(max, nums[j]);
        result[i] = max;
    }
    return result;
}

Correct, but up to ~2.5·109 steps when k ≈ n/2.

At a glance

LevelApproachTimeSpace
Brute ForceRescan Every WindowO(n · k)O(1) extra
BetterMax-Heap with Lazy DeletionO(n log n)O(n)
OptimalMonotonic Decreasing Deque of IndicesO(n)O(k)
Common pitfalls
  • Storing values in the deque — you can no longer tell when the front leaves the window.
  • Checking expiry with the wrong bound: the window is [i-k+1, i].
  • Recording results before the first full window (i < k-1).
Interview tips
  • Explain domination: a smaller, older element is useless once a bigger one arrives.
  • Justify O(n) by amortisation — at most one push and one pop per index.
  • Mention the heap as a stepping stone and why lazy deletion keeps it correct.
Pattern
Monotonic deque → max/min over a sliding window, or DP transitions over a fixed-range window.
My notes saved in this browser