Leaders in an array


Tue Feb 08 2022 05:35:58 GMT+0000 (UTC)

Saved by @Uttam #java #gfg #geeksforgeeks #arrays #practice #leaders

class Solution{
    //Function to find the leaders in the array.
    static ArrayList<Integer> leaders(int arr[], int n){
        int maxEle = arr[n-1];
        ArrayList<Integer> res = new ArrayList<>();
        //We start traversing the array from last element.
        for(int i=n-1; i>=0; i--) {
            //Comparing the current element with the maximum element stored. 
            //If current element is greater than max, we add the element.
		    if(arr[i] >= maxEle){
		        //Updating the maximum element.
		        maxEle = arr[i];
		        //Storing the current element in arraylist for leaders.
		//Reversing the arraylist.
		//returning the arraylist.
        return res;

Leaders in an array Easy Accuracy: 49.96% Submissions: 100k+ Points: 2 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 rightmost 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 <= 10^7 0 <= Ai <= 10^7