Skip to main content
← PROBLEMS / CODING-ALGORITHM
An end-to-end domain learning journey

Sliding Window Maximum with
a Monotonic Deque.

Naive O(N*k) scans or O(N log k) max-heaps with lazy deletion cause GC pressure and p99 latency spikes on 500k events/sec streams; a monotonic decreasing deque computes exact sliding-window maxima in strict O(N) time and O(k) space.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When a single bottleneck threatens end-to-end availability, store indices in a monotonic decreasing deque, evicting expired front indices and smaller back indices so every element is pushed and popped at most once.

TL;DR30-second simplified summary
▾

Core Mechanics: A real-time SLA monitor ingesting 500,000 latency samples/sec (2 microseconds average budget per event) must emit the exact rolling maximum over the last k = 10,000 samples (or W = 5,000 ms).

Visual & Structural Flow: Depicts Lazy-Deletion Max-Heap Bloat vs. Bounded O(1) Deque (500k/s Stream -> Max-Heap (Lazy) -> Monotonic Deque); Three-Step Per-Event State Transition (1. EVICT FRONT -> 2. PRUNE BACK -> 3. PUSH & EMIT).

Trade-Offs & Production: Two subtle mistakes ruin an otherwise good deque solution: Using Python list.pop(0): Shifts all remaining elements in O(k), degrading total runtime back to O(N * k). Maintain a deque of indices whose corresponding values are strictly decreasing from front to back: Front Expiration (O(1)): If dq[0] <= i - k (or ts - dq[0].ts > W for time-based windows), popleft().

Failure Modes & Application: Monotonic deques are used wherever rolling extrema must be tracked over high-frequency streams: Real-Time APM & SLA Monitors: Computes rolling p100/max latency over W = 5,000 ms windows with zero heap churn.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why 500,000 events/sec SLA monitors need O(1) amortized window maxima.

Why this matters: The mechanism: understand how Why 500,000 events/sec SLA monitors need O(1) amortized window maxima works from first principles.

Think of Why 500,000 events/sec SLA monitors need O(1) amortized window maxima as the intuition layer for Sliding Window Maximum with a Monotonic Deque: The mechanism: understand how Why 500,000 events/sec SLA monitors need O(1) amortized window maxima works from first principles.

A real-time SLA monitor ingesting 500,000 latency samples/sec (2 microseconds average budget per event) must emit the exact rolling maximum over the last k = 10,000 samples (or W = 5,000 ms). Scanning k elements takes O(N * k) (5 billion ops/sec), while even O(N log k) heaps introduce GC pressure during bursts.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Lazy-deletion heap bloat and p99 GC pauses under burst traffic.

Why this matters: The problem: see what breaks without Lazy-deletion heap bloat and p99 GC pauses under burst traffic under real concurrency or scale.

Using a max-heap (PriorityQueue / heapq) with lazy deletion fails under high-rate streams:

  1. 100k+ Stale Heap Nodes: When monotonic bursts keep a large old value at the root or delay eviction, the heap swells far beyond k.
  2. GC & O(log N) Allocation Churn: Allocating (value, index) tuples at 500k/sec triggers frequent GC pauses that breach the 2 us budget.
Heap Churn vs. Monotonic Deque

Lazy-Deletion Max-Heap Bloat vs. Bounded O(1) Deque

500k/s StreamMax-Heap (Lazy)Monotonic Deque1. Push (val, idx) 500k/s2. Swells >100k stale nodes -> GC!3. Evict front (<= i-k) & back (<=val)4. Emit dq[0] in O(1) amortized

A monotonic decreasing deque bounds memory to <= k elements and processes each sample in O(1) amortized time.

Engineering Decision Framework
Problem
How to implement Sliding Window Maximum with a Monotonic Deque without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When a single bottleneck threatens end-to-end availability, store indices in a monotonic decreasing deque, evicting expired front indices and smaller back indices so every element is pushed and popped at most once.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Sliding Window Maximum with a Monotonic Deque experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Common implementation bugs: list.pop(0) and storing raw values.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Two subtle mistakes ruin an otherwise good deque solution:

  • Using Python list.pop(0): Shifts all remaining elements in O(k), degrading total runtime back to O(N * k). Always use collections.deque.popleft() (or a fixed ring buffer).
  • Storing raw values instead of indices / (ts, val): Without the index or timestamp, you cannot tell in O(1) whether dq[0] has expired from the window.
Component Topology

Common implementation bugs: list.pop(0) and storing raw values

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Monotonic Decreasing Deque of Indices / Timestamps.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Maintain a deque of indices whose corresponding values are strictly decreasing from front to back:

  • Front Expiration (O(1)): If dq[0] <= i - k (or ts - dq[0].ts > W for time-based windows), popleft().
  • Back Dominance Pruning: While nums[dq[-1]] <= val, pop() from the back—any older element smaller than or equal to val can never be the maximum of any future window.
  • Strict O(N) Time, O(k) Space: Every element is pushed once and popped at most once (<= 2N operations total), keeping memory strictly <= k.
Monotonic Deque Invariant

Three-Step Per-Event State Transition

window validdecreasing order kept1. EVICT FRONTpopleft if idx <= i-k2. PRUNE BACKpop while back <= cur3. PUSH & EMITappend(i); max = dq[0]

Each element enters and leaves the deque at most once, guaranteeing strict O(N) total time and O(k) space.

from collections import deque

def max_sliding_window_count(nums: list[int], k: int) -> list[int]:
    dq = deque()  # stores indices with monotonically decreasing values
    out = []
    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:
            out.append(nums[dq[0]])
    return out
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where monotonic deques power streaming & rate-limiting systems.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Monotonic deques are used wherever rolling extrema must be tracked over high-frequency streams:

  • Real-Time APM & SLA Monitors: Computes rolling p100/max latency over W = 5,000 ms windows with zero heap churn.
  • Adaptive Concurrency & Congestion Control: Tracks min_rtt over a sliding time window (e.g., BBR / Envoy).
  • Financial Tick & Order-Book Engines: Maintains rolling high/low price bounds in O(1) amortized time.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is the monotonic decreasing deque guaranteed to run in `O(N)` total time even though it has an inner `while` loop?

Recommended Learning Flow