Stage 1 · Code
Stacks & Queues
Monotonic Stack
Maintaining sorted stacks for next greater/smaller elements.
Monotonic Stack Concept
A monotonic stack keeps elements in sorted order (strictly increasing or decreasing). When processing a new element, pop elements that violate the order. Each element pushed/popped once → O(n) total.
| Type | Order | Use Case |
|---|---|---|
| Monotonic Increasing | Bottom to top: small → large | Next smaller, previous smaller |
| Monotonic Decreasing | Bottom to top: large → small | Next greater, previous greater |
Next Greater Element
For each element, find the first greater element to its right. Use decreasing stack: pop smaller elements, current is their next greater.
Next Smaller Element
Largest Rectangle in Histogram
Find largest rectangular area in histogram. For each bar, find left/right boundaries where height >= current. Monotonic increasing stack finds previous/next smaller in O(n).
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.