Monotonic Stack for Next Greater Element
Watch which unresolved indices are popped when a greater value arrives.
Core Intuition & How It Works
A monotonic stack maintains elements in strictly increasing or decreasing order by popping any prior items dominated by the incoming value. Each element is pushed once and popped at most once, guaranteeing O(n) total work.
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(n) |
| Space Complexity | O(n) |
| Topic Chapter | Chapter 5: Stacks & Queues |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Store indices (not just values) on the stack so you can compute distances, widths, or populate answer arrays when an index is popped.
Common Pitfalls & Edge Cases
Mis-handling equal elements (strict < vs <=) or thinking the nested while-loop makes the algorithm O(n²) instead of amortized O(n).
Real-World & Technical Interview Applications
Next greater element, daily temperatures, stock span, and largest rectangle in a histogram.