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.
Open on GeeksforGeeks ↗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.
Scanning right-to-left turns a quadratic question into a linear one: a leader must beat everything to its right, and walking backwards means "everything to the right" is a single running maximum. Whenever an element's status depends on all elements on one side, sweep from that side and carry the aggregate.
Approach
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.
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.
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.
Solution & live demo
Common pitfalls
Rescanning the suffix for every element
for i in range(len(nums)):
if all(nums[i] >= nums[j] for j in range(i + 1, len(nums))):
res.append(nums[i])for v in reversed(nums):
if v >= maxRight:
res.append(v); maxRight = vThat's O(n²) and recomputes the same suffix maximum repeatedly. Sweeping backwards keeps it in one variable, so each element is examined once.
Using strict > for the comparison
if v > maxRight:
if v >= maxRight:
GFG defines a leader as greater than or equal to everything on its right, so on [7, 4, 5, 7, 3] both sevens qualify. Strict > drops the first one and returns an answer one element short.
Forgetting to reverse the collected result
return res
res.reverse() return res
Collecting while walking backwards produces the leaders in reverse positional order. The expected output preserves their original left-to-right order.
Edge cases
It is trivially a leader.
Only the last element is a leader.
Every element is a leader.
The >= comparison includes them all, which is what the definition asks for — using > drops the earlier copies.