Monotonic Stack and Deque
Keep a stack or deque in sorted order to answer next greater, previous smaller and window maximum queries in O(n).
Intermediate · about 6 hours · difficulty 4/5
Learn first: Stacks and Queues
A monotonic stack keeps its elements in increasing or decreasing order. When a new element breaks the order, you pop, and each pop answers a question about the popped element. Every element is pushed and popped once, so the whole pass is O(n).
Key patterns
- Next greater element: keep a decreasing stack; when a bigger value arrives, it is the answer for everything it pops (Next Greater Element I and II, Daily Temperatures).
- Previous and next smaller: the boundaries used by Largest Rectangle in Histogram and Maximal Rectangle.
- Contribution technique: count for each element how many subarrays it is the minimum of (Sum of Subarray Minimums).
- Monotonic deque: Sliding Window Maximum keeps indices in decreasing value order and drops ones that leave the window.
- Stock span and asteroid collision: stack-based simulation.
Classic problems
Next Greater Element I, Next Greater Element II (circular, loop 2n), Daily Temperatures, Online Stock Span, Largest Rectangle in Histogram, Maximal Rectangle, Trapping Rain Water (stack version), Sum of Subarray Minimums, Remove K Digits, Asteroid Collision, Sliding Window Maximum.
Pitfalls
- Storing values when you need indices (for distances or widths).
- Handling equal values inconsistently in contribution problems, which double counts subarrays. Use strict on one side and non-strict on the other.
You are ready to move on when you can solve Largest Rectangle in Histogram and explain what each pop computes.
Key concepts
- Next greater and next smaller
- Previous greater and smaller
- Storing indices vs values
- Histogram problems
- Contribution technique
- Monotonic deque for windows
Mini project
Solve these 10 in 7 days, log time and pattern: Next Greater Element I, Next Greater Element II, Daily Temperatures, Online Stock Span, Asteroid Collision, Remove K Digits, Sliding Window Maximum, Largest Rectangle in Histogram, Maximal Rectangle, Sum of Subarray Minimums.
Check yourself
Why is a monotonic stack solution O(n) even though there is a while loop inside the for loop?
Free resources
- takeUforward stack and queue playlist (takeUforward)
- NeetCode roadmap: Stack (NeetCode)
- LeetCode problem set (LeetCode)