Problem
Given an integer array, find all the leader elements in the array.
Definition
An element is said to be a leader if all the elements on its right side are smaller than it. The rightmost element is always a leader.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Iterate from right to left
Here is the approach:
- Traverse the array from right to left.
- Keep track of the maximum element seen so far.
- If the current element is greater than or equal to the maximum element, mark it as a leader.
- The rightmost element is always a leader.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, due to a single traversal of the array. - 🧺 Space complexity:
O(n)
, for storing the leader elements.