AlgoScope

Next Smaller Element

AlgorithmintermediateStack Patterns

The nearest smaller value to the right.

Decision · step 3 of 13Monotonic Stack: Next smaller element
6✓02192431475i6 > 2

2 is smaller than 6, so 2 is the next smaller element of 6. Pop 6, which now has its answer.

Open in the player →or start at step 3

What you will see

Same choreography as next greater with the comparison flipped.

How monotonic stack works →

Cost

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(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.

Leads to

Topics that need this one first.

Taught by the same lesson

Monotonic Stack covers these too, in the same run.