Monotonic Stack
A Monotonic Stack is a Stack maintained in either increasing or decreasing order. When a new element violates that ordering, elements are popped until the invariant is restored. This allows us to efficiently find relationships between an element and the nearest greater or smaller element.
Common problem: Next Greater Element.
Common problem: Next Smaller Element.
Useful for Daily Temperatures.
Useful for Largest Rectangle in Histogram.
Useful for stock span and nearest greater/smaller element problems.
Each element is pushed and popped at most once, giving O(n) total time.
0-2 years experience
2-5 years experience
5-8 years experience
8+ years experience