Monotonic Queue
A monotonic queue is a deque (double-ended queue) where elements are kept in sorted order — increasing or decreasing. It's the go-to tool for the sliding window maximum (or minimum) problem.
The problem it solves
Given an array and a window size k, find the maximum element in every window of size k as it slides across the array.
Example: array = [1, 3, -1, -3, 5, 3, 6, 7], k = 3.
Brute force: For each window, scan all k elements → \(O(n × k)\). With a monotonic queue: \(O(n)\).
← → arrow keys to step · click elements to interact
How it works — the core trick
Maintain a decreasing deque that stores indices (not values). For each new element entering the window:
- Pop from the back while the back element is smaller than the new element. Those elements can never be the maximum — the new element is both newer and larger.
- Push the new index to the back.
- Pop from the front if that index is outside the current window (it's stale).
- The front of the deque is always the index of the window's maximum.
Each index is added and removed at most once, so the total time is \(O(n)\).
Why store indices, not values?
We need to check if an element has slid out of the window. Values don't tell us position — indices do. That's why we store the index and look up the value when needed.
Variations
- For sliding window minimum, flip the comparison: pop when back is greater than the new element (keep an increasing deque).
- Used in DP optimizations when state transitions depend on a range of previous states.