Algo-Sim › Stacks & Monotonic Stack

Sliding Window Maximum

Hard · Stacks & Monotonic Stack · step through it in Java, Python and C++ on your own input

For every window of k consecutive elements, report its maximum.

Problem

A window of size k slides over nums one position at a time, from the far left to the far right. Return the maximum of each window position, in order.

Constraints

Edge cases to test

Follow-up questions

Why a deque of indices, not values?
Indices tell you when the front has left the window; values alone can’t.
What is the heap alternative?
A max-heap of (value, index) with lazy removal of expired tops: O(n log n).
Is there a block trick?
Split into blocks of k with prefix maxima and suffix maxima; each window max is max(suffix[i], prefix[i + k − 1]): O(n).

Solution

Java

public int[] maxSlidingWindow(int[] nums, int k) {
    int n = nums.length;
    int[] result = new int[n - k + 1];
    Deque<Integer> dq = new ArrayDeque<>();
    for (int i = 0; i < n; i++) {
        if (!dq.isEmpty() && dq.peekFirst() <= i - k) {
            dq.pollFirst();
        }
        while (!dq.isEmpty() && nums[dq.peekLast()] < nums[i]) {
            dq.pollLast();
        }
        dq.offerLast(i);
        if (i >= k - 1) {
            result[i - k + 1] = nums[dq.peekFirst()];
        }
    }
    return result;
}

Python

from collections import deque

def max_sliding_window(nums, k):
    result = []
    dq = deque()
    for i in range(len(nums)):
        if dq and dq[0] <= i - k:
            dq.popleft()
        while dq and nums[dq[-1]] < nums[i]:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            result.append(nums[dq[0]])
    return result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    vector<int> maxSlidingWindow(vector<int> &nums, int k) {
        int n = int(nums.size());
        vector<int> result = vector<int>(n - k + 1);
        deque<int> dq = {};
        for (int i = 0; i < n; i++) {
            if (!dq.empty() && dq.front() <= i - k) {
                dq.pop_front();
            }
            while (!dq.empty() && nums[dq.back()] < nums[i]) {
                dq.pop_back();
            }
            dq.push_back(i);
            if (i >= k - 1) {
                result[i - k + 1] = nums[dq.front()];
            }
        }
        return result;
    }
};

More Stacks & Monotonic Stack problems