Sliding Window · Deque

Max in Window Visualizer

What is Max in Window

Return the maximum of every contiguous block of length k, from left to right. A deque stores indices in decreasing order of value. The front index is the max of the current window.

1 3 -1 -3 5 3 6 7
k = 3
3 3 5 5 6 7

Approach

Scan each windowLooking through k values for every start is too slow when both n and k are large.
Keep candidates in a dequeDrop the front index when it slides out of the window. Drop back indices that are smaller than the new value, because they can never be the max while the new value is still inside.

Interactive solution

The window and the deque, max on the left
deque stores indices, largest value at the front
drop the front if it left the window
drop back values that are smaller or equal
push the new index
if the window is full, record the front value
return the maxima
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.

Complexity

PieceCostWhy
TimeO(n)Each index is pushed once and popped once.
MemoryO(k)The deque holds at most one index per window slot.

Implementation

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