Data Structures · Visualization
Monotonic Increasing Stack
Stack
A monotonic increasing stack always keeps its values sorted from bottom (smallest) to top (largest). Time: O(n) total across all pushes/pops (each element is pushed and popped at most once). Space: O(n).
Big-O: push / pop / peek are all O(1).
Monotonic Increasing Stack
StackA monotonic increasing stack always keeps its values sorted from bottom (smallest) to top (largest). Before pushing a new value, you pop off any values from the top that are greater than or equal to the new value, so the increasing order is preserved. This pattern is powerful for efficiently finding, for each element, the nearest smaller value to its left or right.
How Monotonic Increasing Stack Works
- Start with an empty stack.
- For each new value, while the stack is not empty and the top is greater than or equal to the new value, pop it.
- Push the new value onto the stack (it is now the new top).
- Repeat for every element in the input.
Monotonic Increasing Stack Worked Example
Input: Build a monotonic increasing stack from [3, 1, 4, 1, 5]
- Push 3 → [3]
- 1 < 3, pop 3 → []; push 1 → [1]
- 4 >= 1, push 4 → [1, 4]
- 1 <= 4, pop 4 → [1]; 1 <= 1, pop 1 → []; push 1 → [1]
- 5 >= 1, push 5 → [1, 5]
Output: [1, 5]
Press ▶ Run to watch it step by step.
def mono_increasing(arr):
# maintains an increasing stack; pops >= current
stack = [3, 1, 4, 1, 5]
for x in arr:
while stack and stack[-1] >= x:
stack.pop()
stack.append(x)
return stack
# example: monoinc on [3, 1, 4, 1, 5]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Monotonic Increasing Stack Time & Space Complexity
When to Use Monotonic Increasing Stack
- Finding the 'next smaller element' for every item in an array
- Solving histogram-style problems like largest rectangle in a histogram
- Stock span and temperature-trend style problems
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.