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
- A leader is an item greater than every item to its right.
- Scan from the right. The last item is always a leader.
- Keep the maximum seen so far; any item bigger than it is a new leader.
- Reverse the collected leaders to report them in original order.
Watch it run
Loading animation…