Monotonic Stack Visualizer
Scan an array with a monotonic stack, watch indexes push and pop, and see the result array resolve one step at a time.
Array input
Step controls
Step 1 of 17: Scan left to right. The stack stores indexes waiting for a greater value.
Monotonic stack diagram
Scan left to right. The stack stores indexes waiting for a greater value.
Stack
Top of stack appears first.
Result
What is a Monotonic Stack Visualizer?
A monotonic stack visualizer shows how a stack keeps values in increasing or decreasing order while scanning an array.
This tool includes two common patterns: next greater element and previous smaller element. It highlights the current array index, the stack contents, and the result values that become known during each step.
For the full cluster of related tools, browse the Data Structure Visualizers hub.
How to use this monotonic stack visualizer
- Paste an array such as
[2, 1, 2, 4, 3]. - Choose next greater element or previous smaller element.
- Step through every stack push and pop.
- Watch the result array fill as indexes are resolved.
- Use the stack panel to see why each comparison is local.
Why monotonic stacks are useful
Monotonic stacks turn many nested-loop array problems into a single linear scan. The stack keeps only indexes that still need an answer, and each index is pushed and popped at most once.
This pattern appears in next greater element, previous smaller element, daily temperatures, stock span, largest rectangle in histogram, and many range boundary problems.
Compare this page with the Stack and Queue Visualizer, Two Pointers Visualizer, and Merge Intervals Visualizer.