Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Leaders array JavaScript
An element in an array is a leader if it is greater than all elements on its right side. The rightmost element is always a leader since there are no elements to its right.
For example, in the array [23, 55, 2, 56, 3, 6, 7, 1]:
-
56is a leader (greater than 3, 6, 7, 1) -
7is a leader (greater than 1) -
1is a leader (rightmost element)
Input: [23, 55, 2, 56, 3, 6, 7, 1] Output: [56, 7, 1]
Using reduceRight() Method
The most efficient approach is to traverse the array from right to left, keeping track of the maximum element seen so far:
const arr = [23, 55, 2, 56, 3, 6, 7, 1];
const leaderArray = arr => {
const creds = arr.reduceRight((acc, val) => {
let { max, res } = acc;
if(val > max) {
res.unshift(val);
max = val;
}
return { max, res };
}, {
max: -Infinity,
res: []
});
return creds.res;
};
console.log(leaderArray(arr));
[56, 7, 1]
Using Simple Loop Method
A more straightforward approach using a for loop:
const findLeaders = arr => {
const leaders = [];
const n = arr.length;
// Rightmost element is always a leader
let maxFromRight = arr[n - 1];
leaders.push(maxFromRight);
// Traverse from right to left
for (let i = n - 2; i >= 0; i--) {
if (arr[i] > maxFromRight) {
maxFromRight = arr[i];
leaders.push(arr[i]);
}
}
// Reverse to get leaders in original order
return leaders.reverse();
};
const array = [16, 17, 4, 3, 5, 2];
console.log(findLeaders(array));
[17, 5, 2]
How It Works
Both methods use the same logic:
- Start from the rightmost element (always a leader)
- Move left, comparing each element with the maximum seen so far
- If current element is greater than the maximum, it's a leader
- Update the maximum and continue
Comparison
| Method | Time Complexity | Readability |
|---|---|---|
| reduceRight() | O(n) | Functional style |
| For Loop | O(n) | More explicit |
Conclusion
Finding leader elements requires a single right-to-left traversal with O(n) time complexity. Use reduceRight() for functional programming style or a simple loop for better readability.
Advertisements
