March 24
Monotonic Stack
What monotonic stack means, when keeping a stack ordered helps find next greater or smaller values without nested loops.
What it is
A monotonic stack is a stack kept in order.
When a new element breaks that order, you pop until the property is restored.
When to use it
It usually appears when the problem asks for:
- next greater element
- next smaller element
- days until a warmer temperature
- spans
Common mistake
The classic mistake is treating it like an exotic technique.
In practice, it is just an organized way to say:
“some older elements stopped mattering after this one arrived.”
Better question
Before using it, ask:
- does the problem compare each element to future or past neighbors?
- is there a group of elements that loses relevance when another appears?
- am I repeating too many comparisons in nested loops?
Share this page
Copy the link manually from the field below.