"A monotonic stack throws away anything it'll never need again the moment it becomes useless. That ruthless forgetting is what turns an O(n²) 'look ahead' into a single O(n) pass."
The Problem It Solves
Consider: for each element in an array, find the next element to its right that's larger (the "next greater element"). The obvious solution is, for each element, scan rightward until you find a bigger one — O(n²). For a lot of data that's too slow. A monotonic stack solves the whole thing in O(n), and it's one of the most satisfying tricks in this entire quest.
The Idea: Keep the Stack Sorted
A monotonic stack maintains its elements in sorted order — say, decreasing from bottom to top — by popping any element that violates the order before pushing the new one. Here's the magic for "next greater": walk left to right. Before pushing each new value, pop every element on the stack that's smaller than it — because for each of those popped elements, this new value is their next greater element. You've answered them and discarded them in one motion. Anything left on the stack is still waiting for its answer.
Why is this O(n) and not O(n²), given the inner pop-loop? The amortized argument from the Complexity track: each element is pushed exactly once and popped at most once. Total pushes + pops ≤ 2n. The inner loop's total work across the whole run is linear, even though any single step might pop several elements. Counting total operations, not nesting, reveals the O(n).
The Family of Problems
Once you recognize the shape, a whole family opens up: next greater / next smaller element, daily temperatures (how many days until a warmer one), stock span (how many consecutive prior days were lower), and the famous largest rectangle in a histogram. They all share one signal: "for each element, find the nearest element in some direction that beats it." When you hear that, reach for a monotonic stack.