Skip to main content
← CONCEPTS / ALGORITHMS-DATA-STRUCTURES
An end-to-end domain learning journey

Monotonic Deque for O(1)
Amortized Sliding Window Extrema.

Rescanning a k-element sliding window takes O(N*k) time, while lazy heaps accumulate O(N) stale elements on monotonic streams.
Start the journey3 sections· Last modified Nov 28, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When optimizing sliding window extrema, store indices in a monotonic deque so each element enters and exits at most once.

TL;DR30-second simplified summary
▾

Storing indices handles duplicate values cleanly and bounds total work to 2N operations.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Double-ended queue (Deque) O(1) front/back operations
Core prerequisite: Double-ended queue (Deque) O(1) front/back operations.
Aggregate amortized analysis
Core prerequisite: Aggregate amortized analysis.
Full walkthrough · 3 stages
01
STAGE 01L4 · FUNDAMENTALS

The Dominance Invariant.

If j < i and nums[j] <= nums[i], index j can never be the maximum of any window containing i, so we pop j immediately from the back.

Before · Naive
After · Hardened
02
STAGE 02L4 · FUNDAMENTALS

Index-Based Deque Implementation.

Store indices (not raw values) so front expiration checks (dq[0] < i - k + 1) are exact even with duplicate values.

Stream Element iDeque FrontDeque BackResult Array1. Evict while dq[0] < i - k + 1(expired)2. Pop while nums[dq[-1]] <=nums[i] (dominated)3. Append index i to back4. Read nums[dq[0]] in O(1) when i>= k - 1
from collections import deque
def max_sliding_window(nums, k):
    dq, res = deque(), []
    for i, val in enumerate(nums):
        while dq and dq[0] < i - k + 1: dq.popleft()
        while dq and nums[dq[-1]] <= val: dq.pop()
        dq.append(i)
        if i >= k - 1: res.append(nums[dq[0]])
    return res
03
STAGE 03L5 · APPLIED DESIGN

Aggregate Amortization & Cache-Friendly Primitive Arrays.

In Java, replace ArrayDeque<Integer> (boxed Integer objects) with a preallocated int[] array and head/tail pointers for zero GC overhead. [INSERT YOUR BENCHMARK / PROD NOTE] for L1 cache speedup.

Boxed ArrayDeque vs. Primitive int[] Ring Buffer

Before · Boxed ArrayDeque<Integer>
  • Heap-allocated Integer wrappers per push
  • Pointer chasing & GC pressure under high throughput
After · Preallocated int[] Ring Buffer
  • Zero boxing allocations (head/tail int pointers)
  • Contiguous L1-cache-friendly index storage, O(k) fixed memory
Engineering Decision Framework
Problem
Maintain exact rolling maxima or minima over a k-element sliding window (or bounded-jump DP range) in O(1) amortized time and O(k) space.
Naive Solution
Rescan the k-element window at each step, or push (value, index) pairs into a lazy max-heap and discard expired roots on read.
Why It Fails
Rescanning takes O(N * k) time when k is large, while a lazy max-heap incurs O(log N) per push/pop and retains up to O(N) stale entries on monotonic streams.
Alternatives
Segment tree or sparse table for arbitrary static range queries, or two heaps / order-statistic tree when sliding window median or k-th percentile is required.
Engineering Decision
Use a monotonic deque of array indices (backed by a primitive int[] ring buffer in latency-critical Java) for rolling extrema over fixed or monotonic-bound windows.
Trade-Offs
Guarantees <= 2N total deque operations and O(k) memory, at the cost of enforcing index-based front expiration and back dominance invariants; does not support arbitrary k-th order statistics.
Decision Exercise · Make the Call

Why must we store array indices rather than raw values in the monotonic deque?

ChoiceWhat it buysWhat it costs
Brute-Force RescanO(1) extra space Duplicates safeO(N * k) total time Degrades linearly as window k grows
Lazy Max-HeapDuplicates safe Simple heap-based max lookupO(N log N) total time O(N) worst-case space from stale indices
Monotonic DequeO(N) total / O(1) amortized time O(k) bounded space Duplicates safe via indicesRequires maintaining front expiration and back dominance invariants
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 2
Score: 0/2

Why is the nested while loop in the Monotonic Deque algorithm still O(N) overall rather than O(N^2)?

Recommended Learning Flow