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
Finding the element larger than all elements on right - JavaScript
We are required to write a JavaScript function that takes in an array of numbers and returns a subarray that contains all the elements from the original array that are larger than all the elements on their right.
Problem Understanding
For each element in the array, we need to check if it's greater than every element that comes after it. If yes, include it in the result. The last element is always included since there are no elements to its right.
Algorithm Approach
We can solve this efficiently by traversing the array from right to left, keeping track of the maximum element seen so far. If the current element is greater than this maximum, it qualifies for our result.
Example
Following is the code ?
const arr = [12, 45, 6, 4, 23, 23, 21, 1];
const largerThanRight = (arr = []) => {
const creds = arr.reduceRight((acc, val) => {
let { largest, res } = acc;
if(val > largest){
res.push(val);
largest = val;
};
return { largest, res };
}, {
largest: -Infinity,
res: []
});
return creds.res;
};
console.log(largerThanRight(arr));
Output
Following is the output in the console ?
[ 1, 21, 23, 45 ]
How It Works
The function uses reduceRight() to process the array from right to left:
-
Step 1: Start with
largest = -Infinityand empty result array - Step 2: For each element, compare it with the current largest from the right
- Step 3: If current element is larger, add it to result and update largest
- Step 4: Continue until all elements are processed
Alternative Implementation
Here's a more straightforward approach using a traditional loop:
const arr = [12, 45, 6, 4, 23, 23, 21, 1];
function largerThanRightSimple(arr) {
const result = [];
let maxFromRight = -Infinity;
// Traverse from right to left
for (let i = arr.length - 1; i >= 0; i--) {
if (arr[i] > maxFromRight) {
result.unshift(arr[i]); // Add to front to maintain order
maxFromRight = arr[i];
}
}
return result;
}
console.log(largerThanRightSimple(arr));
[ 45, 23, 21, 1 ]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| reduceRight() | O(n) | O(n) | Functional style |
| Traditional loop | O(n) | O(n) | More intuitive |
Conclusion
Both approaches solve the problem efficiently in O(n) time by traversing the array once from right to left. The key insight is tracking the maximum element seen so far from the right side.
