What is Monotonic Stack?
Monotonic Stack maintains elements in sorted order (either increasing or decreasing). It efficiently solves “next greater/smaller” problems in O(n).When to Use
Next Greater Element
Find next larger element for each position
Previous Smaller
Find previous smaller element
Histogram Problems
Largest rectangle, trapping water
Stock Span
Days since last higher price
Pattern Variations
1. Next Greater Element
2. Previous Smaller Element
3. Largest Rectangle in Histogram
4. Daily Temperatures
5. Trapping Rain Water
Classic Problems
| Problem | Stack Type | Key Insight |
|---|---|---|
| Next Greater | Decreasing | Pop smaller, push current |
| Previous Smaller | Increasing | Pop larger or equal |
| Histogram | Decreasing | Calculate area on pop |
| Daily Temperatures | Decreasing | Store indices, compute diff |
| Stock Span | Decreasing | Count days with smaller price |
Practice Problems
Next Greater Element I
Basic monotonic stack
Largest Rectangle
Classic histogram problem
Trapping Rain Water
Multi-approach problem
Sum of Subarray Mins
Contribution technique