Skip to main content
TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN

Monotonic Deque: O(n) Sliding Window Extremes

Maintain a double-ended queue of indices in monotonic order to query sliding-window max/min in O(1) amortized time per step.

monotonic dequesliding windowdequewindow-maxstreaming

The core idea

A monotonic stack answers "next greater element", while a monotonic deque answers "maximum or minimum inside a moving window [i - k + 1 .. i]" in O(n) total time. Store indices (not raw values) so you can evict expired items from the front when dq[0] <= i - k and pop dominated items from the back when nums[dq[-1]] <= nums[i].

Watch it run

Step through the trace below to watch front expiry and back dominance pruning keep dq[0] as the exact window maximum.

LOADING MONOTONIC DEQUE SIM...

Key Takeaway

Canonical Python template

from collections import deque

def max_sliding_window(nums: list[int], k: int) -> list[int]:
    dq: deque[int] = deque()
    out: list[int] = []
    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

Related Lab Entries