To solve the problem of finding leaders in an array, we need to understand what makes an element a leader. A leader is any number in the array that is strictly greater than all the numbers to its right.
We always start checking from the end of the array. This is because the last element has no elements after it, so it is always a leader by definition.
Different Cases Explained
- Case 1: Multiple leaders exist – For example, in
[16, 17, 4, 3, 5, 2]
, we start from the end:
- 2 is a leader (no elements after it)
- 5 > 2, so 5 is a leader
- 3 < 5, so it’s not
- 4 < 5, so skip
- 17 > 5, so it's also a leader
Final leaders in left-to-right order: [17, 5, 2]
- Case 2: Increasing array – In
[1, 2, 3, 4, 5]
, only 5
is a leader because no number is greater than it to the right.
- Case 3: Decreasing array – In
[5, 4, 3, 2, 1]
, each number is greater than the rest of the elements to its right, so every number is a leader.
- Case 4: Equal elements – In
[10, 10, 10]
, only the last 10
is a leader, because the previous ones are not greater than the next.
- Case 5: Single element – Any array with just one element like
[7]
will always have that element as a leader.
- Case 6: Empty array – No elements mean no leaders. Return an empty list.
By starting from the right and keeping track of the maximum element seen so far, we can easily identify all leader elements. Each time we find a new maximum (while scanning from right to left), we record it as a leader.
In the end, we reverse the list of leaders (since we found them from right to left) to return them in left-to-right order as required.
This approach is optimal with a time complexity of O(n) because we only scan the array once.