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.
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
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.