Problem Statement:(👈click here for GFG)
Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader.
Example 1:
Input:
n = 6
A[] = {16,17,4,3,5,2}
Output: 17 5 2
Explanation: The first leader is 17
as it is greater than all the elements
to its right. Similarly, the next
leader is 5. The right most element
is always a leader so it is also
included.
Example 2:
Input:
n = 5
A[] = {1,2,3,4,0}
Output: 4 0
Your Task:
You don't need to read input or print anything. The task is to complete the function leader() which takes array A and n as input parameters and returns an array of leaders in order of their appearance.
Expected Time Complexity: O(n)
Expected Auxiliary Space: O(n)
Constraints:
1 <= n <= 107
0 <= Ai <= 107
Solution:
The approach of this code is to find the leaders in the given array. Leaders are the elements in the array that are greater than all the elements to their right.
The code starts by initializing an array 'leaders' with the last element of the input array 'arr'. It then initializes a variable 'max' with the same value. It then iterates over the elements of the input array from the second last element to the first element. For each element, it checks if it is greater than or equal to 'max'. If it is, it is considered a leader, and it is added to the 'leaders' array, and 'max' is updated to its value. Finally, the 'leaders' array is reversed and returned as the output.
class Solution {
// Function to find the leaders in the array.
leaders(arr) {
const leaders = [arr[arr.length - 1]];
let max = arr[arr.length - 1];
for (let i = arr.length - 2; i >= 0; i--) {
if (arr[i] >= max) {
leaders.push(arr[i]);
max = arr[i];
}
}
return leaders.reverse(); // if you need to console.log the output then simply type console.log(${leaders.reverse()});
}
}
// Prompt the user to enter the array elements.
const arr = prompt("Enter the array elements (comma-separated):").split(",").map((element) => parseInt(element.trim()));
// Create a new instance of the Solution class and call the leaders function.
const solution = new Solution();
const leaders = solution.leaders(arr);
// Output the leaders.
console.log(`The leaders in the array are: ${leaders}`);
Comments
Post a Comment