Skip to content
StackDecode
Stacks & queuesAnimated

Previous Greater Element

Scan left to right, keeping a stack of candidates.

Time

O(n)

Extra space

O(n)

Use it for

Nearest larger value to the left.

How it works

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

Watch it run

Loading animation…