Sliding Window Maximum

HardMonotonic dequeLeetCode 239 ↗World 2-11
0:00 / 0:00

Report the biggest number in every window of k as it slides. Keep a deque of shrinking values, so the front is always the max.

▼

The problem

LeetCode 239 (Hard). Given an integer array nums and a window size k, slide the window from the left end to the right end one position at a time and return the maximum of each window.

Example (LeetCode's): nums = [1,3,-1,-3,5,3,6,7], k = 3 → [3,3,5,5,6,7].

TRY IT ON LEETCODE ▶

The solution

from collections import deque

def maxSlidingWindow(nums, k):
    dq, out = deque(), []
    for i, x in enumerate(nums):
        if dq and dq[0] <= i - k:
            dq.popleft()
        while dq and nums[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out

Transcript

Sliding Window Maximum. A window of size k slides along a list of numbers. At every step, report the biggest number inside it. Each number is a fish, and the window is a porthole.

Take one, three, minus one, minus three, five, three, six, seven, with k of three. The first window holds one, three and minus one: its biggest is three. The six windows give three, three, five, five, six, seven.

The simple way rescans every window: k looks each, order n times k. A million numbers with a window of a thousand is about a billion looks, mostly repeats.

Here's the trick. When a big fish arrives, every smaller fish in the window is hopeless: it's smaller and leaves sooner, so it can never be the biggest again. The big fish eats it. The survivors line up from biggest to smallest.

Keep survivors as indices in a deque, a line open at both ends. For each new fish: first, if the front fish has left the window, drop it. Second, pop from the back every fish no bigger than the newcomer. Third, push the newcomer. Now the front is the window's biggest.

Let's play the example. One joins, and three eats it. Minus one waits behind three. The window is full: the max is three. Minus three joins: still three. Three swims out of the front, and five eats both minus fish: five. Three waits behind five: five. Six eats three and five: six. Seven eats six: seven.

In code: loop over the indices and values. If the front index is out of range, pop it from the left. While the back's value is at most the new one, pop it. Append the index. Once the first window is full, record the front's value.

Each index joins the deque once and leaves at most once: order n time, however big k is. The deque never holds more than k fish: order k space.

Drop the old, eat the small, read the front. That's Sliding Window Maximum.