Skip to contentKEEP THE CRAFTTHE SANCTUARY

Monotonic Queue

Maintain live window candidates in a deque with the strongest value at the front. Expiration removes old fronts, dominance removes weaker backs, and these different reasons make constant-time access to the current maximum possible.

1 practice exercise1 interview problem

Recognize it when Every complete moving window needs its maximum or minimum.

Checking your account…

Monotonic Queue Code Labs

Find What a Rolling Sum Cannot Remember

A fixed window sum can subtract its outgoing contribution. A maximum cannot subtract the old maximum and reveal the next best value. Keep a deque of candidates instead: each candidate is an index, so its value and its expiration time are both available.

Remove Age and Dominance at Different Ends

At processed index i, the complete window starts at i-width+1. A front index <= i-width is stale and must leave. From the back, an older value no greater than the entering value is dominated: the newer one is at least as strong and remains available longer. These Labs keep the newer equal value, making candidate values strictly decreasing.

Trace Monotonic Deque State

Reference
from collections import deque

def max_deque_trace(values,width):
    candidates=deque(); trace=[]
    for index,value in enumerate(values):
        while candidates and candidates[0]<=index-width: candidates.popleft()
        while candidates and values[candidates[-1]]<=value: candidates.pop()
        candidates.append(index); trace.append(list(candidates))
    return trace
Practice

Implement max_deque_trace(values,width). Return deque index contents after processing each index for sliding maximum. width is a positive integer.

Public tests

  • Expire and remove dominated indexes

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Trace Monotonic Deque State

from collections import deque

def max_deque_trace(values,width):
    candidates=deque(); trace=[]
    for index,value in enumerate(values):
        while candidates and candidates[0]<=index-width: candidates.popleft()
        while candidates and values[candidates[-1]]<=value: candidates.pop()
        candidates.append(index); trace.append(list(candidates))
    return trace

Expire an Old Maximum before Reading the Next Front

With values [9, 4, 7, 2] and width 2, the existing trace shows age removal and back domination in the same iteration.

Step Executed statement State Why
First candidate candidates.append(index); trace.append(list(candidates)) index=0, candidates=[0] This partial window has one live maximum candidate.
Weaker arrival candidates.append(index); trace.append(list(candidates)) index=1, candidates=[0,1], values=[9,4] 4 is weaker but may survive after 9 expires.
Expire 9 while candidates and candidates[0]<=index-width: candidates.popleft() index=2, candidates=[1] Index 0 is outside the new window [1,2].
Dominate 4 while candidates and values[candidates[-1]]<=value: candidates.pop() value=7, candidates=[] The newer 7 is stronger than 4 and lasts longer.
Append 7 candidates.append(index); trace.append(list(candidates)) trace=[[0],[0,1],[2]] Index 2 now owns the maximum candidate.
Retain weaker 2 return trace final candidates=[2,3]; trace=[[0],[0,1],[2],[2,3]] The last value may matter only after the older 7 expires.
Print Output
print(max_deque_trace([9, 4, 7, 2], 2)) [[0], [0, 1], [2], [2, 3]]

Read a Maximum Only for a Complete Window

The trace Lab records candidate indices even before width values have entered. The maximum Lab emits only after index >= width-1. Once stale fronts and dominated backs are removed, the front is strongest among all remaining live candidates. Expiration and dominance are distinct proofs; changing one removal end breaks a different part of the invariant.

Compute Sliding Window Maximums

Reference
from collections import deque

def window_maximums(values,width):
    candidates=deque(); result=[]
    for index,value in enumerate(values):
        while candidates and candidates[0]<=index-width: candidates.popleft()
        while candidates and values[candidates[-1]]<=value: candidates.pop()
        candidates.append(index)
        if index>=width-1: result.append(values[candidates[0]])
    return result
Practice

Implement window_maximums(values,width). Return the maximum for every complete fixed-width window. width is a positive integer.

Public tests

  • Read the strongest live front

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Compute Sliding Window Maximums

from collections import deque

def window_maximums(values,width):
    candidates=deque(); result=[]
    for index,value in enumerate(values):
        while candidates and candidates[0]<=index-width: candidates.popleft()
        while candidates and values[candidates[-1]]<=value: candidates.pop()
        candidates.append(index)
        if index>=width-1: result.append(values[candidates[0]])
    return result

Include Diagnostic Copies and Heap Retention

The core scan is O(n), with at most k candidates and output proportional to the number of complete windows. The trace copies the deque every step, so decreasing input with a large width can produce O(nk) observations, capped at O(n²). A lazy-deletion heap is more general but can retain stale entries below its root; its worst-case storage and logarithmic operation cost depend on retained entries, not automatically only k.

Explain Each Removal in an Interview

Say whether a candidate leaves because its index expired or because a newer value dominates it. Check width one, a width larger than the input and repeated equal maxima. Then transfer to a bounded spread by maintaining two independent deques rather than confusing a maximum candidate list with the entire window.

Template To Memorize

Learn this shape by heart; most problems in this family change only one or two lines of it.

Monotonic queue (sliding window maximum)

Bigger newcomer clears the back; the front is the max; drop the front when it leaves.

You need the maximum (or minimum) of every window as the window slides.

Trigger words

  • sliding window maximum
  • max of every window
  • window max and min
  • deque of candidates
from collections import deque

def window_maxes(nums, k):
    window = deque()                 # indexes; their values decrease from front to back
    maxes = []
    for right, num in enumerate(nums):
        while window and nums[window[-1]] <= num:
            window.pop()             # smaller values can never be the max again
        window.append(right)
        if window[0] <= right - k:
            window.popleft()         # the front slid out of the window
        if right >= k - 1:
            maxes.append(nums[window[0]])
    return maxes

Spot it when

  • 'Maximum of every window of size k'.
  • A window must track its max and min at the same time.

Remember

  • Store indexes, not values, so you can tell when the front has left the window.
  • Every index is added once and removed at most once: O(n).

How problems bend it

  • Window minimum: Flip the comparison: pop from the back while nums[window[-1]] >= num.
  • Window whose max - min must stay within a limit: Keep one decreasing deque for the max and one increasing deque for the min; shrink the left side while max - min is too big.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Sliding maximum core scanO(n)O(n)Each index enters once and leaves at most once; both pop loops have O(n) total removals.

Space

O(k) candidate space plus O(n) returned maxima; full deque snapshots use O(n min(k,n)) output.

Assumptions

  • Width is positive. The diagnostic Lab converts candidates to a list every step, costing O(n min(k,n)) worst-case time and output; it includes partial-window states.
  • collections.deque supports fast removals at both ends; list.pop(0) shifts remaining elements and cannot justify the same linear bound.

Invariants Worth Saying Aloud

  1. Deque indices increase front to back and all are inside the current processed window.
  2. Candidate values strictly decrease because the actual Labs remove older equal values; the front is the strongest live value.

When To Use Or Avoid Monotonic Queue

Use It When

  • Compute fixed-width maxima with live candidate indices rather than recomputing max on every slice.
  • Maintain both a maximum and minimum deque for range-spread constraints after defining separate orders.

Choose Another Tool When

  • Use a rolling total for sums; extrema cannot be updated by subtracting the outgoing maximum.
  • Use a heap for more general priority retrieval, accounting for stale entries and its actual retained heap size.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Keeping the index exactly at the expiration cutoff

At index 2 with width 2, index 0 is already outside [1,2]. A strict < cutoff leaves its maximum 9 in the answer.

Prevent it: Expire candidates <= index-width before reading the front.

Avoid

while candidates and candidates[0] < index-width:
    candidates.popleft()

Use instead

while candidates and candidates[0] <= index-width:
    candidates.popleft()

Comparing index magnitude instead of candidate value

An index 0 is numerically <= entering value 2, but its stored value 8 is stronger and should remain.

Prevent it: Dereference candidate indices through values before comparing priority.

Avoid

while candidates and candidates[-1] <= value:
    candidates.pop()
candidates.append(index)

Use instead

while candidates and values[candidates[-1]] <= value:
    candidates.pop()
candidates.append(index)

Expiring from the back

When the oldest index is stale, pop removes the newest candidate instead and leaves the expired maximum at the front.

Prevent it: Age order increases from front to back, so use popleft for expiration and pop only for dominance.

Avoid

candidates.pop()

Use instead

candidates.popleft()

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.