20
Monotonic Stack
Next or previous greater/smaller element.
4 pages
- Pattern 20: Monotonic StackPattern guide
One-line trigger: "For each element, find the next / previous element that is greater / smaller."
- LC 739Daily Temperatures (LC 739)Medium
Keep a stack of indices whose answer is still unknown, in decreasing temperature order. A warmer day resolves several of them at once.
- LC 496Next Greater Element I (LC 496)Easy
Precompute every next-greater answer for nums2 in one O(n) pass, store it in a map, then answer each nums1 query in O(1).
- LC 84Largest Rectangle in Histogram (LC 84)Hard
For each bar, the widest rectangle of that bar's height is bounded by the first strictly smaller bar on each side. A monotonic increasing stack finds both…