Find all elements that are strictly greater than all elements to their right.
Problem Statement
Given an array `arr` of integers, find all the leaders in the array.
An element is called a leader if it is greater than or equal to all elements to its right side. The rightmost element is always a leader.
Return the leaders in the order they appear from left to right.
Examples
Input: arr = [16, 17, 4, 3, 5, 2]
Output: [17, 5, 2]
Explanation: 17 is greater than 4, 3, 5, 2. 5 is greater than 2. 2 has no elements to its right.
Input: arr = [1, 2, 3, 4, 0]
Output: [4, 0]
Explanation: Elements in [4, 0] are greater than all elements to their right.
Complexity
Time Complexity: O(N)
Space Complexity: O(1)
Hints
š” Hint 1:
An element is a leader if it is greater than or equal to all elements to its right.
š” Hint 2:
Scanning from right to left allows tracking the current maximum element to the right in O(1).
š” Hint 3:
Whenever arr[i] >= maxFromRight, it is a leader. Collect and reverse at the end.
Editorial & Approach
Problem Overview & Intuition
Checking from left to right would require an O(N) search for each element (O(N²)). By traversing from right to left, we maintain maxFromRight in O(1) time per element.
Step-by-Step Approach
- Initialize
result = []andmaxFromRight = -Infinity. - Iterate
ifromarr.length - 1down to0. - If
arr[i] >= maxFromRight, pusharr[i]toresultand updatemaxFromRight = arr[i]. - Reverse
resultto maintain original left-to-right order, then return it.
Optimal Implementation (JavaScript)
function leaders(arr) {
const result = [];
let maxFromRight = -Infinity;
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] >= maxFromRight) {
result.push(arr[i]);
maxFromRight = arr[i];
}
}
return result.reverse();
}
Complexity Analysis
Time Complexity
O(N) ā single traversal plus reversal.
Space Complexity
O(1) auxiliary space (excluding output array).
Edge Cases & Corner Traps Handled
- The last element is always a leader.
- Strictly increasing array: only the last element is leader.
- Strictly decreasing array: every element is a leader.