Builds onStack
01The idea
A monotonic stack is a stack whose items stay in order, always increasing or always decreasing from bottom to top. Before you push a new item, you pop every item that would break the order.
The pops are not lost work. An item gets popped because the new item makes it useless. Take "the nearest smaller value to the left". Suppose 7 sits on the stack and 4 arrives. For every number after 4, the 4 is closer than the 7 and is also smaller. So 7 can never be anyone's answer again, and we pop it.
After the pops, the top of the stack is exactly the answer for the new item. Then push the new item, because it may be the answer for later items.
The loop pushes every item once and pops it at most once. So the whole pass is O(n), even with a while loop inside the for loop.
02How to spot it
Use a monotonic stack when the problem asks, for every item:
- the nearest item to the left or right that is bigger or smaller
- how many days until a warmer day, a higher price or a taller building
- how far an item can stretch before something smaller or bigger blocks it, as in the largest rectangle in a bar chart
The brute force for these checks every earlier or later item, which is O(n²). The word "nearest" or "next" combined with "bigger" or "smaller" is the strongest signal.
To choose the order, ask which items stay useful. For "previous smaller", keep an increasing stack and pop items that are bigger or equal. For "previous bigger", keep a decreasing stack and pop items that are smaller or equal. For "next" instead of "previous", you can walk from the right, or record answers for the popped items as you walk from the left.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue