Skip to content
StackDecode
Stacks & queuesAnimated

Next Smaller Element

Same idea with the comparison reversed.

Time

O(n)

Extra space

O(n)

Use it for

Next smaller value to the right.

How it works

  1. For each item we want the first smaller item to its right.
  2. Scan left to right with a stack of items waiting for an answer.
  3. A new item smaller than the top is its answer: pop and record.
  4. Push the new item. Leftovers have no answer.

Watch it run

Loading animation…