DSA Master › Topic 8
Stack & Monotonic Stack
A stack handles anything nested or last-in-first-out, like brackets or expressions. A monotonic stack keeps its elements in sorted order. When a new element breaks that order, you pop, and each pop answers a "next greater" or "previous smaller" question in O(n) total.
Concepts
- Monotonic increasing/decreasing stacks
- Expression evaluation
- Stack simulation
How to recognise it
- The problem asks for the next or previous greater/smaller element.
- You're matching brackets, evaluating expressions or simulating collisions.
- You need the largest rectangle or span for each element.
Common pitfalls
- Push indices, not values, when you need distances or widths.
- Use ArrayDeque, not the legacy Stack class.
Problems
- Valid Parentheses (Easy)
- Min Stack (Medium)
- Evaluate Reverse Polish Notation (Medium)
- Daily Temperatures (Medium)
- Next Greater Element I (Easy)
- Largest Rectangle in Histogram (Hard)
- Online Stock Span (Medium)
- Remove K Digits (Medium)
- Asteroid Collision (Medium)