For each element, what is the next greater element to its right? The monotonic stack answers all of them in a single pass. It holds the indices of values still waiting for their answer, kept in decreasing order. Each new value resolves everything on top of the stack it exceeds (they have found their next-greater — it is the newcomer), popping them, then joins the stack to wait its own turn. Every element is pushed once and popped once: O(n) for what looks like an O(n²) question. The stack is the bounded memory of “questions not yet answered,” and it drains as answers arrive.
A short array. The demo finds the next-greater-element of the first value, using the monotonic stack: live demo
“Next-greater-element is a quadratic scan.” — a stack of the undecided makes it linear: each value waits once and is resolved once, the instant a larger value appears. cited
A stack of open questions; each newcomer closes the ones it towers over. Linear answers to a quadratic-looking ask. monotonic stack
On the canonical compiler, the next-greater-element of 2 in [2,1,5,3] is 5 — found in one forward pass: