Previous Greater Element
The nearest larger value to the left, via a monotonic stack.
Decision · step 3 of 14Monotonic Stack: Previous greater element
4 is greater than 3, so 4 is the previous greater element of 3. Push 3.
What you will see
After popping smaller values, the stack top is the answer.
Cost
| Best | O(n) |
|---|---|
| Average | O(n) |
| Worst | O(n) |
| Space | O(n) |
How you work with it here
play it through, step one change at a time, scrub to any step, run it on your own input, predict what happens next, try operations in any order.
Screen readers: Items announce position from the top or front and value; each step announces the operation and the new top or front.
Reduced motion: Items appear or disappear in place with a crossfade instead of sliding in or out.
Before this
A variant of
Taught by the same lesson
Monotonic Stack covers these too, in the same run.