Monotonic Stack
Keep a stack in increasing or decreasing order to find the next greater or smaller item efficiently.
The question asks for the next warmer day, next greater element, histogram rectangle, or nearest smaller boundary.
How to approach it
Scan once, popping while the current value resolves the stack top; push the current index to preserve distance information.
Choose strictly greater versus greater-or-equal behavior deliberately, especially when equal values appear.
Practice question
For each value, find the next greater value to its right in [2, 1, 3, 2, 4].
values = [2, 1, 3, 2, 4]Give your answer before revealing the explanation.Show a hint
Keep indices of values that have not yet seen a greater value.
Show an answer
[3, 3, 4, 4, -1]
Monotonic Stack at work
For daily temperatures [18, 20, 17, 22], how many days must you wait after each day for a warmer temperature?
Show one possible approach
[1, 2, 1, 0]. The next warmer temperatures are 20, 22, 22, and none. A decreasing stack keeps days still waiting for a warmer reading.
Practice next
Use these problem IDs to find additional practice for this pattern: