Sliding Window Extrema
In short: a monotonic stack only ever removes from one end, which is fine until old items need to expire out of a sliding window whether or not anything beat them. A deque gives a second exit: new arrivals evict dominated items from the back, and the front is evicted when it slides out of the window. What's left is always sorted, so the front is always the window's max (or min) — and every index enters and leaves once, so the whole scan is O(n) no matter how big the window is.

Quarry's live dashboard draws a band under its latency graph: for the last k
requests, the fastest and the slowest. Every new request shifts the window by one,
so the band has to be recomputed for every request. Rescanning the window each time
costs O(k) per request and O(n·k) for a trace. With k = 1000 and a busy engine,
that's a thousand comparisons for every request served, just to draw a line.
The previous lesson's stack answered "who is the next bigger one?" because items only ever left from the top. A window needs a second exit: old requests expire off the far end whether or not anything beat them. A structure with two exits is a deque, and a deque kept in sorted order is a monotonic deque.
Three moves, one invariant
You met the sliding-window maximum briefly in the queues lesson. Here is the idea
again, stated so it can be reused. Keep a deque of indices whose latencies
decrease from front to back. For each new request i:
- Evict from the back every index whose latency is less than or equal to the new one. While the new request is in the window, those can never be the maximum, because it is at least as slow and it will stay longer.
- Push
ionto the back. - Evict from the front if the front index has slid out of the window, which
is when it is
<= i - k.
After those moves the front is the window's maximum. It's the oldest survivor, and everything behind it is smaller.
Watch the deque on that trace. The front, on the left, is always the answer:
New requests evict weaker ones from the back, and time evicts old ones from the front. What's left is always sorted, so the front is the window's worst request.
Request 0 enters an empty deque. Deque, 1 item. Head is 40 (#0), tail is 40 (#0).
Each index enters the deque once and leaves at most once, from one end or the
other, so the whole pass is O(n) whatever k is.