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.
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.
Index-Based Deque Implementation.
Store indices (not raw values) so front expiration checks (dq[0] < i - k + 1) are exact even with duplicate values.
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
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
- Heap-allocated Integer wrappers per push
- Pointer chasing & GC pressure under high throughput
- Zero boxing allocations (head/tail int pointers)
- Contiguous L1-cache-friendly index storage, O(k) fixed memory
- 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.
Why must we store array indices rather than raw values in the monotonic deque?
| Choice | What it buys | What it costs |
|---|---|---|
| Brute-Force Rescan | O(1) extra space Duplicates safe | O(N * k) total time Degrades linearly as window k grows |
| Lazy Max-Heap | Duplicates safe Simple heap-based max lookup | O(N log N) total time O(N) worst-case space from stale indices |
| Monotonic Deque | O(N) total / O(1) amortized time O(k) bounded space Duplicates safe via indices | Requires maintaining front expiration and back dominance invariants |
Practice: Make the trade-off yourself.
Why is the nested while loop in the Monotonic Deque algorithm still O(N) overall rather than O(N^2)?