The Wayback Machine - https://web.archive.org/web/20240818163942/https://www.geeksforgeeks.org/leaders-in-an-array/
Open In App

Leaders in an array

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Write a program to print all the Leaders in the array. An element is a Leader if it is greater than all the elements to its right side.

Note: The rightmost element is always a leader.

Examples:

Input: arr[] = {16, 17, 4, 3, 5, 2}
Output: 17 5 2
Explanation:

  • 17 is greater than all the elements to its right: 4, 3, 5 and 2, therefore 17 is a leader.
  • 5 is greater than all the elements to its right: 2, therefore 5 is a leader.
  • 2 has no element to its right, therefore 2 is a leader.

Input: arr[] = {1, 2, 3, 4, 5, 2}
Output: 5 2
Explanation:

  • 5 is greater than all the elements to its right: 2, therefore 5 is a leader.
  • 2 has no element to its right, therefore 2 is a leader.

Approaches to find Leaders in an array:

[Naive Approach] Using Nested Loops – O(N^2) Time and O(1) Space:

Use two loops. The outer loop runs from 0 to size – 1 and one by one pick all elements from left to right. The inner loop compares the picked element to all the elements on its right side. If the picked element is greater than all the elements to its right side, then the picked element is the leader.

Below is the implementation of the above approach:

C++
#include <iostream>
using namespace std;

/*C++ Function to print leaders in an array */
void printLeaders(int arr[], int size)
{
    for (int i = 0; i < size; i++) {
        int j;
        for (j = i + 1; j < size; j++) {
            if (arr[i] <= arr[j])
                break;
        }
        if (j == size) // the loop didn't break
            cout << arr[i] << " ";
    }
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 16, 17, 4, 3, 5, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printLeaders(arr, n);
    return 0;
}
C
/*C Function to print leaders in an array */

#include <stdio.h>

void printLeaders(int arr[], int size)
{
    int i, j;
    for (i = 0; i < size; i++) {
        for (j = i + 1; j < size; j++) {
            if (arr[i] <= arr[j])
                break;
        }
        if (j == size) // the loop didn't break
            printf("%d ", arr[i]);
    }
}

/* Driver program to test above function */
int main()
{
    int arr[] = { 16, 17, 4, 3, 5, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printLeaders(arr, n);
    return 0;
}
Java
import java.io.*;
public class LeadersInArray {
    /*Java Function to print leaders in an array */
    void printLeaders(int arr[], int size)
    {
        for (int i = 0; i < size; i++) {
            int j;
            for (j = i + 1; j < size; j++) {
                if (arr[i] <= arr[j])
                    break;
            }
            if (j == size) // the loop didn't break
                System.out.print(arr[i] + " ");
        }
    }

    /* Driver program to test above functions */
    public static void main(String[] args)
    {
        LeadersInArray lead = new LeadersInArray();
        int arr[] = new int[] { 16, 17, 4, 3, 5, 2 };
        int n = arr.length;
        lead.printLeaders(arr, n);
    }
}
Python
# Python Function to print leaders in array


def printLeader(arr, n):
    for i in range(n):
        k = False
        for j in range(i+1, n):
            if(arr[i] <= arr[j]):
                k = True
                break
        else: # If loop did not break
            print(arr[i], end=' ')


# Driver function
arr = [16, 17, 4, 3, 5, 2]
printLeader(arr, len(arr))
C#
// C# program to print
// leaders in array
using System;
class GFG {
    void printLeaders(int[] arr, int size)
    {
        for (int i = 0; i < size; i++) {
            int j;
            for (j = i + 1; j < size; j++) {
                if (arr[i] <= arr[j])
                    break;
            }

            // the loop didn't break
            if (j == size)
                Console.Write(arr[i] + " ");
        }
    }

    // Driver Code
    public static void Main()
    {
        GFG lead = new GFG();
        int[] arr = new int[] { 16, 17, 4, 3, 5, 2 };
        int n = arr.Length;
        lead.printLeaders(arr, n);
    }
}
JavaScript
// Javascript Function to print leaders in an array

function printLeaders(arr, size) {
    for (let i = 0; i < size; i++) {
        let j;
        for (j = i + 1; j < size; j++) {
            if (arr[i] <= arr[j])
                break;
        }
        if (j == size) // the loop didn't break
            console.log(arr[i] + " ");
    }
}
// driver code 

let arr = [16, 17, 4, 3, 5, 2];
let n = arr.length;

// Function calling 
printLeaders(arr, n);

Output
17 5 2 

Time Complexity: O(N * N), where N is the number of elements in the array.
Auxiliary Space: O(1)

[Expected Approach] Using Suffix Maximum – O(N) Time and O(1) Space:

The idea is to scan all the elements from right to left in an array and keep track of the maximum till now. When the maximum changes its value, print it.

Illustration:

Let the array be arr[] = {16, 17, 4, 3, 5, 2}

  • arr[] = {16, 17, 4, 3, 5, 2 } , max_from_right = 2, ans[] = { 2 }
  • arr[] = {16, 17, 4, 3, 5 , 2} , max_from_right = 5, ans[] = { 2, 5 }
  • arr[] = {16, 17, 4, 3 , 5, 2} , max_from_right = 5, ans[] = { 2, 5 }
  • arr[] = {16, 17, 4 , 3, 5 , 2} , max_from_right = 5, ans[] = { 2, 5 }
  • arr[] = {16, 17 , 4, 3, 5, 2} , max_from_right = 17, ans[] = { 2, 5, 17 }
  • arr[] = { 16 , 17, 4, 3, 5, 2} , max_from_right = 17, ans[] = { 2, 5, 17 }

Below is the implementation of the above approach.

C++
#include <iostream>
using namespace std;

/* C++ Function to print leaders in an array */
void printLeaders(int arr[], int size)
{
    int max_from_right =  arr[size-1];

    /* Rightmost element is always leader */
    cout << max_from_right << " ";
    
    for (int i = size-2; i >= 0; i--)
    {
        if (max_from_right < arr[i]) 
        {           
            max_from_right = arr[i];
            cout << max_from_right << " ";
        }
    }    
}

/* Driver program to test above function*/
int main()
{
    int arr[] = {16, 17, 4, 3, 5, 2};
    int n = sizeof(arr)/sizeof(arr[0]);
    printLeaders(arr, n);
    return 0;
}    
C
#include <stdio.h>

/* C Function to print leaders in an array */
void printLeaders(int arr[], int size)
{
    int max_from_right = arr[size - 1];

    /* Rightmost element is always leader */
    printf("%d ", max_from_right);

    for (int i = size - 2; i >= 0; i--) {
        if (max_from_right < arr[i]) {
            max_from_right = arr[i];
            printf("%d ", max_from_right);
        }
    }
}

/* Driver program to test above function*/
int main()
{
    int arr[] = { 16, 17, 4, 3, 5, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    printLeaders(arr, n);
    return 0;
}
Java
import java.io.*;
public class LeadersInArray 
{
    /* Java Function to print leaders in an array */
    void printLeaders(int arr[], int size)
    {
        int max_from_right =  arr[size-1];
 
        /* Rightmost element is always leader */
        System.out.print(max_from_right + " ");
     
        for (int i = size-2; i >= 0; i--)
        {
            if (max_from_right < arr[i])
            {           
            max_from_right = arr[i];
            System.out.print(max_from_right + " ");
            }
        }    
    }

    /* Driver program to test above functions */
    public static void main(String[] args) 
    {
        LeadersInArray lead = new LeadersInArray();
        int arr[] = new int[]{16, 17, 4, 3, 5, 2};
        int n = arr.length;
        lead.printLeaders(arr, n);
    }
}
Python
# Python function to print leaders in array
def printLeaders(arr, size):
   
    max_from_right = arr[size-1]   
    print (max_from_right,end=' ')    
    for i in range( size-2, -1, -1):        
        if max_from_right < arr[i]:        
            print (arr[i],end=' ')
            max_from_right = arr[i]
        
# Driver function
arr = [16, 17, 4, 3, 5, 2]
printLeaders(arr, len(arr))
C#
// C# program to find Leaders in an array
using System;

class LeadersInArray {
    
    // C# Function to print leaders
    // in an array 
    void printLeaders(int []arr, int size)
    {
        int max_from_right = arr[size - 1];

        // Rightmost element is always leader
        Console.Write(max_from_right +" ");
    
        for (int i = size - 2; i >= 0; i--)
        {
            if (max_from_right < arr[i])    
            {     
                max_from_right = arr[i];
                Console.Write(max_from_right +" ");
            }
        } 
    }

    // Driver Code
    public static void Main(String[] args) 
    {
        LeadersInArray lead = new LeadersInArray();
        int []arr = new int[]{16, 17, 4, 3, 5, 2};
        int n = arr.Length;
        lead.printLeaders(arr, n);
    }
}
JavaScript
/* JavaScript Function to print leaders in an array */
function printLeaders(arr, size) {
    let max_from_right = arr[size - 1];

    /* Rightmost element is always leader */
    console.log(max_from_right + " ");

    for (let i = size - 2; i >= 0; i--) {
        if (max_from_right < arr[i]) {
            max_from_right = arr[i];
            console.log(max_from_right + " ");
        }
    }
}


let arr = [16, 17, 4, 3, 5, 2];
let n = arr.length;
printLeaders(arr, n);

Output
2 5 17 

Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Javascript Program for Leaders in an array
Write a program to print all the LEADERS in the array. An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader. For example int the array {16, 17, 4, 3, 5, 2}, leaders are 17, 5 and 2. Let the input array be arr[] and size of the array be size. Recommended: Please solve it on "PRAC
2 min read
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES Explanation: Replacing input[1] with (input[0] +
10 min read
Find Array formed by adding each element of given array with largest element in new array to its left
Given an array A of size N, the task is to find the resultant array formed by adding each element of the given array with the largest element in the new array to its left.Examples: Input: arr[] = {5, 1, 6, -3, 2} Output: {5, 6, 12, 9, 14} Element A0: No element if present at its left. Hence the element at 0th index of the resultant array = 5 Elemen
6 min read
Array obtained by repeatedly reversing array after every insertion from given array
Given an array arr[], the task is to print the array obtained by inserting elements of arr[] one by one into an initially empty array, say arr1[], and reversing the array arr1[] after every insertion. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4 2 1 3Explanation:Operations performed on the array arr1[] as follows:Step 1: Append 1 into the array a
6 min read
Maximize product of array by replacing array elements with its sum or product with element from another array
Given two arrays A[] and B[] consisting of N integers, the task is to update array A[] by assigning every array element A[i] to a single element B[j] and update A[i] to A[i] + B[j] or A[i] * B[j], such that the product of the array A[] is maximized. Note: Every array element in both the arrays can be paired with a single element from the other arra
7 min read
Reduce array to longest sorted array possible by removing either half of given array in each operation
Given an array arr[] of size N (always power of 2), the task is to find the length of the longest sorted array to which the given array can be reduced by removing either half of the array at each operation. Examples: Input: arr[] = { 11, 12, 1, 2, 13, 14, 3, 4 }Output: 2 Explanation: Removal of the first half of arr[] modifies arr[] to {13, 14, 3,
8 min read
Sum of Bitwise OR of each array element of an array with all elements of another array
Given two arrays arr1[] of size M and arr2[] of size N, the task is to find the sum of bitwise OR of each element of arr1[] with every element of the array arr2[]. Examples: Input: arr1[] = {1, 2, 3}, arr2[] = {1, 2, 3}, M = 3, N = 3Output: 7 8 9Explanation: For arr[0]: Sum = arr1[0]|arr2[0] + arr1[0]|arr2[1] + arr1[0]|arr2[2], Sum = 1|1 + 1|2 + 1|
11 min read
Convert an array into Bitonic array by right shifting array elements
Giver an array arr[] consisting of N integers, the task is to perform right shift operations on array elements to convert the given array into a bitonic array. Examples: Input: arr[] = {7, 3, 4, 5, 3}Output: 56 96 128 80 48Explanation:Perform the operation on the array elements as: 7 ? 00000111 ? 3 right shifts ? 00111000 ? 563 ? 00000011 ? 5 right
11 min read
Sum of array elements possible by appending arr[i] / K to the end of the array K times for array elements divisible by K
Given an array arr[] consisting of N integers and an integer K, the task is to find the sum of the array elements possible by traversing the array and adding arr[i] / K, K number of times at the end of the array, if arr[i] is divisible by K. Otherwise, stop the traversal. Examples: Input: arr[] = {4, 6, 8, 2}, K = 2Output: 44Explanation:The followi
14 min read
Construct array B as last element left of every suffix array obtained by performing given operations on every suffix of given array
Given an array arr[] of N integers, the task is to print the last element left of every suffix array obtained by performing the following operation on every suffix of the array, arr[]: Copy the elements of the suffix array into an array suff[].Update ith suffix element as suff[i] = (suff[i] OR suff[i+1]) - (suff[i] XOR suff[i+1]) reducing the size
9 min read
Modify array by making all array elements equal to 0 by subtracting K^i from an array element in every i-th step
Given an array arr[] of size N, the task is to check if it is possible to convert all array elements to 0s, by subtracting Ki from an array element, in the ith step. If it is possible to do so, then print "Yes". Otherwise, print "No". Examples: Input: N = 5, K = 2, arr[] = {8, 0, 3, 4, 80}Output: YesExplanation: One possible sequence of operations
8 min read
Check whether an array can be fit into another array rearranging the elements in the array
Given two arrays A and B of the same size N. Check whether array A can be fit into array B. An array is said to fit into another array if by arranging the elements of both arrays, there exists a solution such that the ith element of the first array is less than or equal to ith element of the second array. Examples: Input : A[] = { 7, 5, 3, 2 }, B[]
6 min read
Find original array from encrypted array (An array of sums of other elements)
Find original array from a given encrypted array of size n. Encrypted array is obtained by replacing each element of the original array by the sum of the remaining array elements. Examples : Input : arr[] = {10, 14, 12, 13, 11} Output : {5, 1, 3, 2, 4} Original array {5, 1, 3, 2, 4} Encrypted array is obtained as: = {1+3+2+4, 5+3+2+4, 5+1+2+4, 5+1+
6 min read
Find an element in array such that sum of left array is equal to sum of right array
Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4, 5] Input: 1 2 3Output: -1Explanation: No sub-arr
15+ min read
Merge an array of size n into another array of size m+n
There are two sorted arrays. First one is of size m+n containing only m elements. Another one is of size n and contains n elements. Merge these two arrays into the first array of size m+n such that the output is sorted. Input: array with m+n elements (mPlusN[]). NA =&gt; Value is not filled/available in array mPlusN[]. There should be n such array
12 min read
Sum of elements in given range from Array formed by infinitely concatenating given array
Given an array arr[](1-based indexing) consisting of N positive integers and two positive integers L and R, the task is to find the sum of array elements over the range [L, R] if the given array arr[] is concatenating to itself infinite times. Examples: Input: arr[] = {1, 2, 3}, L = 2, R = 8Output: 14Explanation:The array, arr[] after concatenation
10 min read
Map elements of an array to elements of another array
Given two arrays A and B of positive integers, elements of array B can be mapped to elements of array A only if both the elements have same value. The task is to compute the positions in array A to which elements of array B will be mapped. Print NA if mapping for a particular element cannot be done. Note: For one position only one integer can be ma
6 min read
Divide every element of one array by other array elements
Given two arrays and the operation to be performed is that the every element of a[] should be divided by all the element of b[] and their floor value has to be calculated. Examples : Input : a[] = {5, 100, 8}, b[] = {2, 3} Output : 0 16 1 Explanation : Size of a[] is 3. Size of b[] is 2. Now 5 has to be divided by the elements of array b[] i.e. 5 i
6 min read
Find element in array that divides all array elements
Given an array of n non-negative integers. Find such element in the array, that all array elements are divisible by it. Examples : Input : arr[] = {2, 2, 4}Output : 2 Input : arr[] = {2, 1, 3, 1, 6}Output : 1 Input: arr[] = {2, 3, 5}Output : -1 Brute Force Approach: The brute force approach to solve this problem would be to iterate through all the
7 min read
Closest greater element for every array element from another array
Given two arrays a[] and b[], we need to build an array c[] such that every element c[i] of c[] contains a value from a[] which is greater than b[i] and is closest to b[i]. If a[] has no greater element than b[i], then value of c[i] is -1. All arrays are of same size. Examples: Input : a[] = [ 2, 6, 5, 7, 0] b[] = [1, 3, 2, 5, 8] Output : c[] = [2,
5 min read
Generate original array from an array that store the counts of greater elements on right
Given an array of integers greater[] in which every value of array represents how many elements are greater to its right side in an unknown array arr[]. Our task is to generate original array arr[]. It may be assumed that the original array contains elements in range from 1 to n and all elements are unique Examples: Input: greater[] = { 6, 3, 2, 1,
5 min read
Find Sum of all unique sub-array sum for a given array.
Given an array of n-positive elements. The sub-array sum is defined as the sum of all elements of a particular sub-array, the task is to find the sum of all unique sub-array sum. Note: Unique Sub-array sum means no other sub-array will have the same sum value. Examples: Input : arr[] = {3, 4, 5} Output : 40 Explanation: All possible unique sub-arra
10 min read
Maximum in an array that can make another array sorted
Given two arrays among which one is almost sorted with one element being in the wrong position making the array unsorted, the task is to swap that element with the maximum element from the second array which can be used to make the first array sorted. Examples: Input: arr1 = {1, 3, 7, 4, 10}, arr2 = {2, 1, 5, 8, 9} Output: 1 3 7 9 10 Swap 4 with 9.
8 min read
Construct an array from GCDs of consecutive elements in given array
Given an array a[] of n elements. The task is to find the array (say b[]) of n + 1 such that Greatest Common Divisor of b[i] and b[i + 1] is equals to a[i]. If multiple solutions exist, print the one whose array sum is minimum. Examples: Input : a[] = { 1, 2, 3 } Output : 1 2 6 3 GCD(1, 2) = 1 GCD(2, 6) = 2 GCD(6, 3) = 3 Also, 1 + 2 + 6 + 3 = 12 wh
7 min read
Convert the array such that the GCD of the array becomes 1
Given an array of positive elements and a positive integer k, the task is to convert the GCD of the array to 1. To make it possible, only one operation is allowed any number of times i.e. choose any element of the array &amp; divide with a number d where d &lt;= k. Examples: Input : arr = {10, 15, 30}, k = 6 Output : Yes Divide all the elements of
9 min read
Generate an N-length array having GCD of all its pairs present in a given 2D array
Given a 2D array arr[][] consisting of N*N positive integers, the task is to generate an N-length array such that Greatest Common Divisors(GCD) of all possible pairs of that array is present in the array arr[][]. Examples: Input: N = 4, arr[] = {2, 1, 2, 3, 4, 3, 2, 6, 1, 1, 2, 2, 1, 2, 3, 2}Output: 4, 3, 6, 2Explanation:Considering the array A[] a
8 min read
Minimum count of array elements that must be changed such that difference between maximum and minimum array element is N - 1
Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements that must be changed to any arbitrary integers such that the difference between maximum and minimum array element is (N - 1) and all array elements must be distinct. Examples: Input: arr[] = {1, 2, 3, 5, 6}Output: 1Explanation:Change 6-&gt;4, the
7 min read
Find the Initial Array from given array after range sum queries
Given an array arr[] which is the resultant array when a number of queries are performed on the original array. The queries are of the form [l, r, x] where l is the starting index in the array, r is the ending index in the array and x is the integer elements that have to be added to all the elements in the index range [l, r]. The task is to find th
13 min read
For each element in 1st array count elements less than or equal to it in 2nd array | Set 2
Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]. Examples: Input : arr1[] = [1, 2, 3, 4, 7, 9] arr2[] = [0, 1, 2, 1, 1, 4] Output : [4, 5, 5, 6, 6, 6] Explanation: There are 4 elements less than or equal to 1 in second array, similarly there
13 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg