Skip to content
StackDecode
Stacks & queuesAnimated

Next Greater Element

A stack of waiting items resolves each when a bigger one arrives.

Time

O(n)

Extra space

O(n)

Use it for

For each item, the next larger one to its right.

How it works

  1. For each item we want the first larger item to its right.
  2. Scan left to right with a stack of items still waiting for their answer.
  3. When a new item is larger than the item on top of the stack, it is that item’s answer: pop and record.
  4. Then push the new item. Items left at the end have no answer.

Watch it run

Loading animation…