Sliding Window Maximum

Pattern: Monotonic deque

hard

Keep a deque of indexes whose values decrease from front to back. A new value removes smaller values from the back (they can never be a maximum again); the front leaves once it is outside the window. The front is the maximum of every full window.

The problem

Return the maximum of every window of k neighbouring values, in order. [1, 3, -1, -3, 5, 3, 6, 7] with k = 3 gives [3, 3, 5, 5, 6, 7].

Think first

  • When can a value never again be a window's maximum?
  • Which end of the window does each value leave from?
  • Why keep indexes?

Hints

    Brute force, and why it fails

    Scan every window: O(n × k). A max-heap with lazy deletion is O(n log n).

    The key insight

    Keeping only values that could still become the maximum leaves a decreasing sequence, and its front is the current maximum.

    Dry run

    10 
    31 
    -12 
    -33 
    54 
    35 
    66 
    77 
    deque3 -1
    out[3]

    nums = [1, 3, -1, -3, 5, 3, 6, 7], k = 3. 3 removes 1; push -1. Window [1, 3, -1]: max 3.

    Step 1 of 4

    The plan

    for i, v in nums:
        while dq and nums[dq.back] <= v: dq.pop_back()
        dq.push_back(i)
        if dq.front <= i - k: dq.pop_front()
        if i >= k - 1: out.append(nums[dq.front])
    

    Complexity

    Time
    O(n)
    Space
    O(k)

    Each index is added once and removed once.

    Edge cases

    • k = 1: the array itself.
    • k = n: one value.
    • Decreasing array: the deque holds the whole window.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int[] maxSlidingWindow(int[] nums, int k) {
            int n = nums.length;
            int[] out = new int[n - k + 1];
            Deque<Integer> dq = new ArrayDeque<>();         // indexes, values decreasing from front to back
            for (int i = 0; i < n; i++) {
                while (!dq.isEmpty() && nums[dq.peekLast()] <= nums[i]) dq.pollLast();   // smaller and older: never a max
                dq.addLast(i);
                if (dq.peekFirst() <= i - k) dq.pollFirst();   // the front left the window
                if (i >= k - 1) out[i - k + 1] = nums[dq.peekFirst()];
            }
            return out;
        }
    }

    C++

    class Solution {
    public:
        vector<int> maxSlidingWindow(vector<int>& nums, int k) {
            vector<int> out;
            deque<int> dq;                                  // indexes, values decreasing from front to back
            for (int i = 0; i < static_cast<int>(nums.size()); i++) {
                while (!dq.empty() && nums[dq.back()] <= nums[i]) dq.pop_back();   // smaller and older: never a max
                dq.push_back(i);
                if (dq.front() <= i - k) dq.pop_front();    // the front left the window
                if (i >= k - 1) out.push_back(nums[dq.front()]);
            }
            return out;
        }
    };

    Python

    from collections import deque
    
    class Solution:
        def maxSlidingWindow(self, nums: list[int], k: int) -> list[int]:
            out, dq = [], deque()                   # dq: indexes, values decreasing from front to back
            for i, v in enumerate(nums):
                while dq and nums[dq[-1]] <= v:
                    dq.pop()                        # smaller and older: never a max
                dq.append(i)
                if dq[0] <= i - k:
                    dq.popleft()                    # the front left the window
                if i >= k - 1:
                    out.append(nums[dq[0]])
            return out

    Common mistakes

    • Checking the window with < instead of <= and keeping a stale front.
    • Recording answers before the first full window.

    Similar problems