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.

Values
5
Stack
0
Current
-
Resolved
0

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.

Current In stack Resolved
Input array
Stack keeps unresolved indexes in decreasing value order.
0
2
1
1
2
2
3
4
4
3
Next greater value
?
0
?
1
?
2
?
3
?
4

Stack

Top of stack appears first.

Stack is empty.

Result

mode = Next greater
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.

Frequently Asked Questions

What does monotonic mean in a stack?
It means the values represented by the stack are kept in sorted order, either increasing or decreasing, after each scan step.
Why does the monotonic stack store indexes instead of values?
Indexes let the algorithm update the result for a specific position while still comparing values from the original array.
What is the time complexity of a monotonic stack?
Most monotonic stack scans are O(n) because every index is pushed once and popped at most once.
Which problems use a monotonic stack?
Common examples include next greater element, daily temperatures, stock span, largest rectangle in histogram, and previous smaller element.

Related tools