QueueHard

Sliding Window Maximum Visualizer

What is Sliding Window Maximum

Return the maximum of every contiguous window of length k. A deque of indexes, kept in decreasing order of value, makes each index enter and leave once.

Approach

Recomputing the max of every window is too slow when n is 100000. The deque answers each window in amortized constant time.

Visualization & algorithm

The window and the deque of candidates
deque of indexes, values decreasing
drop front if it left the window
pop back while it is <= the new value
push i
when the window is full, answer is a[front]
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start from the first step. The controls sit under the picture and the pseudocode.

Complexity

PieceCostWhy
TimeO(n)Each index is pushed and popped at most once.
SpaceO(k)The deque never holds more than one decreasing run.

Implementation

from collections import deque
def solve(self, nums, k):
    dq, ans = deque(), []
    for i, val in enumerate(nums):
        if dq and dq[0] <= i-k: dq.popleft()
        while dq and nums[dq[-1]] <= val: dq.pop()
        dq.append(i)
        if i >= k-1: ans.append(nums[dq[0]])
    return ans