A Monotonic Stack is a specialized stack whose elements are strictly maintained in a sorted monotonic order—either strictly increasing or strictly decreasing. This pattern is the secret weapon for solving range-lookup problems (like Next Greater Element, Daily Temperatures, and Largest Rectangle in Histogram) in single-pass $O(n)$ linear time instead of brute-force $O(n^2)$.
1. Real-World Analogy: Waiting for a Taller Person
Imagine people standing in a line waiting at a bus stop:
A person looks forward into the distance.
Shorter people in front of them are completely blocked from view by the first person who is taller than them.
Once a giant steps into the line, all shorter people standing behind them are overshadowed. A monotonic decreasing stack maintains this exact line of sight!
2. The Two Types of Monotonic Stacks
1
Monotonically Increasing Stack: Elements from bottom to top are in increasing order ($1 \to 3 \to 5 \to 8$).
Used to find the Previous/Next Smaller Element.
1
Monotonically Decreasing Stack: Elements from bottom to top are in decreasing order ($8 \to 5 \to 3 \to 1$).
Used to find the Previous/Next Greater Element.
1Algorithm Rule for Monotonic Decreasing Stack (Next Greater Element):
2Before pushing element X:
3While stack is not empty AND stack.top() < X:
4 pop() element (because X is the "Next Greater Element" for the popped item!)
5push(X)
3. Classic Problem: Daily Temperatures
Given an array of daily temperatures temperatures, return an array answer such that answer[i] is the number of days you have to wait after the $i$-th day to get a warmer temperature. If there is no future day with a warmer temperature, keep answer[i] == 0.