GeeksforGeeks Easy

Leaders in an Array

An element is a leader if it is greater than or equal to every element to its right. Return all leaders in the order they appear.

arraysuffix
Open on GeeksforGeeks ↗
02

Intuition

💡

The definition compares each element against everything to its right, which pulls you straight into an O(n^2) double loop. Read it once more, though: beating every element on the right is the same as beating their maximum. That is one number, not a scan. Walk right to left carrying that running maximum and the inner loop disappears. One detail decides correctness at the end — compare with >=, not >, or duplicate maxima that genuinely qualify get dropped.

03

Approach

1

Collapse the inner loop into one number

Comparing against every element on the right is the same as comparing against their maximum, since if you beat the largest you beat them all. That single observation turns an O(n^2) check into an O(1) one.

2

Sweep right to left

Only a right-to-left sweep has the suffix maximum available when you need it. Start with maxRight as negative infinity — or simply take the last element, which is always a leader since nothing lies to its right.

3

Collect and reverse

If nums[i] >= maxRight, record it as a leader and set maxRight = nums[i]. Use >= so that the last occurrence of a repeated maximum still qualifies, matching the problem's definition. The leaders come out in reverse order, so reverse the list at the end to restore the original order. O(n) time, O(1) auxiliary space beyond the output.

04

Solution & live demo

python
1class Solution:
2 def leaders(self, nums):
3 res = []
4 maxRight = float('-inf')
5 for v in reversed(nums):
6 if v >= maxRight:
7 res.append(v)
8 maxRight = v
9 # else: someone bigger sits to the right
10 res.reverse()
11 return res
05

Edge cases

Single element

It is trivially a leader.

Strictly increasing array

Only the last element is a leader.

Strictly decreasing array

Every element is a leader.

Duplicate maxima

The >= comparison includes them all, which is what the definition asks for — using > drops the earlier copies.

06

Complexity

Time
O(n)
Space
O(1)
Excluding the output. The suffix-maximum idea replaces the O(n^2) double loop.