DSA · Reimagined
Stacks & Queues hard time O(n) space O(n)

Monotonic Stack — Next Greater

Keep a stack of values still waiting for an answer. When a bigger value arrives, it answers everything smaller on the stack at once. Each value is pushed and popped at most once, so the whole thing is linear.

array
2
0
1
1
5
2
6
3
2
4
3
5
stack (still waiting)
next greater
0
1
2
3
4
5

For each value find the next greater value to its right, using a stack of values still waiting.

1 / 20

Practice

Machine twin: /dsa-viz-v2/monotonic-stack.json — the full deterministic run as structured data.