Array Leaders

easy

You are given an array arr of non-negative integers. Find all the leaders in the array.

An element is a leader if it is greater than or equal to every element to its right. The rightmost element is always a leader (there is nothing to its right to beat it).

Return the leaders in the same left-to-right order in which they appear in arr.

Hints

For any element, what is the only thing to its right that could disqualify it from being a leader?
The rightmost element is always a leader. What if you build the answer starting from that end?
Sweep right-to-left carrying the maximum seen so far; an element is a leader exactly when it is at least that running maximum.

Common doubts

Yes. The rule is greater-than-or-equal, so compare with >=. That is why [10, 4, 2, 4, 1] keeps both 4s.
In their original left-to-right order in arr. If you collect them by scanning from the right, reverse the list before returning.
Yes. Values start at 0, so initialize your running maximum to negative infinity (or INT_MIN) rather than 0.

Interview follow-ups

Track the index during the same backward sweep; push (i, arr[i]) when arr[i] >= maxRight, then reverse.
Switch the comparison from >= to >; equal neighbors on the right would then disqualify an element.

Fun facts

  • The trick is a suffix-maximum: precompute or stream the max of every suffix and a leader is any element meeting its own suffix max.
  • The same running-extreme sweep reappears in stock span, next-greater-element, and trapping-rain-water problems.

Asked at

AmazonAdobeMicrosoftFlipkart
Frequently Sometimes Occasionally
Example 1
Input: arr = [16, 17, 4, 3, 5, 2]
Output: [17, 5, 2]
Nothing to the right of 17, 5, or 2 is larger than them.
Example 2
Input: arr = [10, 4, 2, 4, 1]
Output: [10, 4, 4, 1]
Both 4s qualify — an equal element on the right still lets a value be a leader.
Example 3
Input: arr = [5, 10, 20, 40]
Output: [40]
In a strictly increasing array, only the last element is a leader.
Constraints

- 1 <= arr.size <= 10^6 - 0 <= arr[i] <= 10^6

Solve this problem →