Menu
CoddyTech

Leaders in an Array

You get an array of integers nums. An element is a leader when it is greater than or equal to every element to its right. The last element has nothing to its right, so it is always a leader. Return every leader, in the order they appear in nums from left to right.

Function

leaders(nums: integer-array) → integer-array
numsinteger-array
the array of integers to search
Returnsinteger-array
the leaders of nums, from left to right

Constraints

  • 1 ≤ nums.length ≤ 25000
  • -109 ≤ nums[i] ≤ 109

Examples

Input
nums = [12, 5, 9, 3, 6, 2]
Output
[12, 9, 6, 2]
Explanation
2 is last, so it leads. 6 beats the 2 after it, 9 beats 3, 6 and 2, and 12 beats everything. 5 loses to 9 and 3 loses to 6, so the answer is [12, 9, 6, 2].
challenge icon

Follow-up

If the values arrive one at a time and after each you must report the leaders so far, how do you update the list in O(1) amortized time per value?

Reset code
def leaders(nums):
    # Write code here

Test #1

Test #2

Test #3

Argument

nums = [12, 5, 9, 3, 6, 2]

Expected Output

[12, 9, 6, 2]