Next Smaller Element
The nearest smaller value to the right.
Decision · step 3 of 13Monotonic Stack: Next smaller element
2 is smaller than 6, so 2 is the next smaller element of 6. Pop 6, which now has its answer.
What you will see
Same choreography as next greater with the comparison flipped.
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.