Skip to content
StackDecode
Stacks & queuesAnimated

Previous Smaller Element

Scan left to right with an increasing stack.

Time

O(n)

Extra space

O(n)

Use it for

Nearest smaller value to the left.

How it works

  1. For each item we want the nearest smaller item to its LEFT.
  2. Scan left to right keeping a stack of candidates in increasing order.
  3. Pop candidates that are not smaller than the current item.
  4. The item left on top is the answer; then push the current item.

Watch it run

Loading animation…