Skip to content
StackDecode
Array techniquesAnimated

Leaders in an Array

Scan from the right keeping the maximum; each new maximum is a leader.

Time

O(n)

Extra space

O(1)

Use it for

Elements greater than everything to their right.

How it works

  1. A leader is an item greater than every item to its right.
  2. Scan from the right. The last item is always a leader.
  3. Keep the maximum seen so far; any item bigger than it is a new leader.
  4. Reverse the collected leaders to report them in original order.

Watch it run

Loading animation…