Data Structures · Visualization
Monotonic Decreasing Stack
Stack
A monotonic decreasing stack keeps its values sorted from bottom (largest) to top (smallest) — the mirror image of the increasing version. Time: O(n) total across all pushes/pops. Space: O(n).
Big-O: push / pop / peek are all O(1).
Monotonic Decreasing Stack
StackA monotonic decreasing stack keeps its values sorted from bottom (largest) to top (smallest) — the mirror image of the increasing version. Before pushing a new value, you pop off any values from the top that are less than or equal to the new value, so the decreasing order is preserved. This is the go-to pattern for efficiently finding the nearest greater value to the left or right of each element.
How Monotonic Decreasing Stack Works
- Start with an empty stack.
- For each new value, while the stack is not empty and the top is less than or equal to the new value, pop it.
- Push the new value onto the stack.
- Repeat for every element in the input.
Monotonic Decreasing Stack Worked Example
Input: Build a monotonic decreasing stack from [2, 6, 3, 8]
- Push 2 → [2]
- 6 >= 2, pop 2 → []; push 6 → [6]
- 3 <= 6, push 3 → [6, 3]
- 8 >= 3, pop 3 → [6]; 8 >= 6, pop 6 → []; push 8 → [8]
Output: [8]
Press ▶ Run to watch it step by step.
def mono_decreasing(arr):
# maintains a decreasing stack; pops <= current
stack = [2, 6, 3, 8]
for x in arr:
while stack and stack[-1] <= x:
stack.pop()
stack.append(x)
return stack
# example: monodec on [2, 6, 3, 8]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 Decreasing Stack Time & Space Complexity
When to Use Monotonic Decreasing Stack
- Finding the 'next greater element' for every item in an array
- Daily temperatures style problems (how many days until a warmer day)
- Sliding window maximum 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.