When solving sliding window extrema under tight memory/latency budgets, use an index-based Monotonic Deque.
TL;DR30-second simplified summary▾
Each index is pushed once and popped at most once, giving O(N) total time and O(k) space.
Why Lazy Heaps Fail on Decreasing Streams.
If nums = [N, N-1, ..., 1], the root is popped only once per step while pushed elements accumulate, leaving O(N) stale nodes in memory.
Zero-Allocation Java Ring Deque.
Use a preallocated primitive int[] array in Java to avoid Integer boxing overhead under 1M+ samples/sec.
int[] dq = new int[n];
int head = 0, tail = 0;
for (int i = 0; i < n; i++) {
while (head < tail && dq[head] < i - k + 1) head++;
while (head < tail && nums[dq[tail - 1]] <= nums[i]) tail--;
dq[tail++] = i;
if (i >= k - 1) res[i - k + 1] = nums[dq[head]];
}
Boundary & Edge-Case Invariants.
Handle k = 1, k > n, and all-equal arrays cleanly by checking i >= k - 1 after both eviction loops. [INSERT YOUR BENCHMARK / PROD NOTE] for throughput.
Boundary & Edge-Case Invariants
- Reads expired dq[head] if checked late
- O(k) duplicates when using strict <
- Expire front (< i - k + 1) before read
- Emit only when i >= k - 1 (handles k=1, k>n)
- Problem
- Maintaining exact sliding-window maxima or minima at 1M+ samples/sec under strict latency and O(k) memory bounds.
- Naive Solution
- Rescan each k-element window in O(N*k) time or push every sample into a lazy-deletion Max-Heap / PriorityQueue.
- Why It Fails
- Rescanning hits 10^11 ops (TLE) at N=10^6, while lazy heaps accumulate O(N) stale nodes beneath valid maxima on decreasing or skewed streams and pay O(log N) per push.
- Alternatives
- Index-based Monotonic Deque (O(N) time, O(k) space), Segment Tree / Sparse Table (O(N log N) or O(N) build with higher memory), or dual-heap for non-monotonic order statistics.
- Engineering Decision
- Use an index-based Monotonic Decreasing Deque (backed by a primitive int[] ring buffer in Java) whenever the aggregate is monotonic (max/min); reserve heaps or balanced trees for non-monotonic aggregates like rolling median.
- Trade-Offs
- Guarantees O(1) amortized time per element and <= k live entries with zero Integer autoboxing, at the cost of only supporting monotonic extrema rather than arbitrary rank queries.
What happens if you check front expiration AFTER reading nums[dq[0]] instead of before?
| Choice | What it buys | What it costs |
|---|---|---|
| Strictly Decreasing Stream | Monotonic Deque stays O(k) space and O(N) time | Lazy Max-Heap bloats to O(N) stale nodes and O(N log N) time |
| Strictly Increasing Stream | Both Lazy Max-Heap and Monotonic Deque stay O(1) live size | Lazy Max-Heap still pays O(log k) heapify overhead per push |
| All-Equal Stream | Monotonic Deque with <= eviction stays O(1) size | Lazy Max-Heap retains up to O(k) duplicate entries in window |
Practice: Make the trade-off yourself.
On a strictly decreasing array of length N with window k, what is the peak size of a lazy Max-Heap?