Program to Print all the Leaders in the array in Java

Hello everyone! Today we will Write a Program to print all the Leaders in the array in Java. So you are given an array and you have to find the leaders. A leader in an array is the element which is greater than all elements to its right side. You can solve this problem in different approaches but here I will show you a simple one with an explanation in Java.

Let’s see an example and understand the problem:

Input: 10, 30, 6, 12, 2
Output:30 12 2

Input: 20, 54, 2, 84, 3
Output:84 3

Input: 12, 67, 8, 5
Output:67 8 5

So, you can see from the examples that all output element has no greater element to is right. The last element in the array will always be printed because there is no element right to it.

In the first example, you can see that after 10 there is a greater element that is 30. So 10 can’t appear in the output. For 30 there is no such element, so it must be in our output. And 12 is after 6, so 6 is not considered. 12 is the largest from the right side. The last element is always considered in our output because it is the rightmost element. So the output is-[ 30 12 2]. Now you can easily figure out the output of the other examples.

Now, see the algorithm:
Declare a variable and initialize it with the minimum possible number in Java. Then traverse the array from the right side and if any element is bigger than the variable then store it in a different array.
At last, print the array in reverse order and you will get the desired output.

Now see the implementation-

import java.util.*; 
class Main  
{ 
    //Function to print leaders in an array 
    void getLeaders(int arr[], int n)  
    { 
        int temp=Integer.MIN_VALUE;//initialize temp variable with min value
        Vector vec=new Vector();
        for(int i=n-1;i>=0;i--){//traverse the array from right side
            if(arr[i]>temp){
                vec.add(arr[i]);
                temp=arr[i];
            }
        }
        Collections.reverse(vec);//reverse the vector
        Iterator i = vec.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());//print the vector
      }
    } 
  
    public static void main(String[] args)  
    { 
        Main solution = new Main(); 
        int arr[] = new int[]{20, 10, 13, 3, 6, 2}; //input array
        int n = arr.length; 
        solution.getLeaders(arr, n); 
    } 
}
Output:
20
13
6
2

The time complexity of the algorithm is O(n). I hope, you understand the solution. Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *