March 24
Monotonic Queue
What monotonic queue means, when keeping a queue ordered helps answer window max or min efficiently.
What it is
A monotonic queue is a queue kept in order so the best candidate in the current window is easy to access.
It usually stores indices, not only values.
When to use it
It appears often when the problem asks for:
- window maximum
- window minimum
- sliding-window queries for the best element
Common mistake
The classic mistake is thinking “if there is a queue, I can just enqueue everything.”
If you do not remove elements that became irrelevant, the queue loses its advantage.
Better question
Before using it, ask:
- does the window move one step at a time?
- do I need the best element of the window all the time?
- have some older elements become strictly worse than the newer ones?
Share this page
Copy the link manually from the field below.