150NeetCode 150

20.Sliding Window Maximum

HardSliding Window · 6/6

Problem

You are given an integer array nums and a window size k. A window of size k slides from the left end of the array to the right end, one position at a time.

Return an array containing the maximum value of each window — there are n - k + 1 windows in total.

Examples

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

Constraints

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

💡 Key Insight

Once a larger element arrives, every smaller element to its left can never be a window maximum again — the larger one is newer and outlives them. So keep a deque of indices whose values are strictly decreasing: pop smaller values from the back when a new element arrives, and pop the front when it slides out of the window. The front is always the current maximum, and each index is pushed and popped once.

Brute Force

TimeO(n · k)SpaceO(1)

Intuition

For each of the n - k + 1 windows, scan its k elements and take the maximum.

Algorithm

  1. Create result of size n - k + 1.
  2. For each start i, compute max(nums[i..i+k-1]) and store it in result[i].
  3. Return result.

Visualization

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

i=0: max(1, 3, -1)  = 3
i=1: max(3, -1, -3) = 3
i=2: max(-1, -3, 5) = 5
...  each window rescanned from scratch

Code

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

Complexity

  • Time: O(n · k) — up to 10^10 operations at the limits, which times out.
  • Space: O(1) — excluding the output.

Complexity Comparison

Approach Time Space
Brute Force O(n · k) O(1)
Max-Heap (lazy deletion) O(n log n) O(n)
Monotonic Deque O(n) O(k)

Common Pitfalls

  • Storing values instead of indices in the deque — then you cannot tell when the front has left the window (duplicates make it ambiguous).
  • Using b[0] - a[0] style comparators is safe here only because values are within ±10^4; for wider ranges use Integer.compare to avoid overflow.
  • Comparing Integer objects with == (e.g. dq.peekFirst() == i - k works because one side is an int and unboxing happens; comparing two Integers with == would not be safe).
  • Writing the output before the first full window exists — only emit once i >= k - 1.