Skip to content
Related Articles

Related Articles

Improve Article

Count greater elements on the left side of every array element

  • Last Updated : 31 May, 2021

Given an array arr[] of distinct integers of size N, the task is to print the count of greater elements on the left side of each array element.

Examples :

Input: arr[] = {12, 1, 2, 3, 0, }
Output: 0 1 1 1 4
Explanation:
For index 0, no greater element exists on the left side.
For index 1, {12} is greater element on the left side.
For index 2, {12} is greater element on the left side.
For index 3, {12} is greater element on the left side.
For index 4, {12, 1, 2, 3} are greater elements on the left side.
Therefore, the output is 0 1 1 1 4.

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

Naive Approach: The simplest approach to solve the problem is to traverse the array and for every array element, traverse towards its left and compare every element with the current element. Finally, print the count of greater elements on its left for every array element. 



Time Complexity: O(N2
Auxiliary Space: O(1)

Efficient Approach: The problem can be solved using Set containers which are implemented by Self Balancing Binary Search Tree. Follow the steps below solve the problem.

  1. Create an empty Set, St.
  2. Traverse the array and insert every element in St one by one.
  3. Find the previous greater element of arr[i] using upper_bound function.
  4. Find the distance between the previous greater element and the last element of the set using the distance function.
  5. Store the distance in the array, countLeftGreater[].
  6. Print the array.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to print the count of greater
// elements on left of each array element
void display(int countLeftGreater[], int N)
{
    for (int i = 0; i < N; i++) {
        cout << countLeftGreater[i]
             << " ";
    }
}
 
// Function to get the count of greater
// elements on left of each array element
void countGreater(int arr[], int N)
{
    // Store distinct array
    // elements in sorted order
    set<int> St;
 
    // Stores the count of greater
    // elements on the left side
    int countLeftGreater[N];
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Insert array elements
        // into the set
        St.insert(arr[i]);
 
        // Find previous greater element
        auto it = St.upper_bound(arr[i]);
 
        // Find the distance between the
        // previous greater element of arr[i]
        // and last element of the set
        countLeftGreater[i]
            = distance(it, St.end());
    }
    display(countLeftGreater, N);
}
 
// Driver Code
int main()
{
    int arr[] = { 12, 1, 2, 3, 0, 11, 4 };
    int N = sizeof(arr) / sizeof(arr[0]);
    countGreater(arr, N);
}

Java




// Java program to implement
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
     
// Function to print the count of greater
// elements on left of each array element
static void display(int countLeftGreater[], int N)
{
    for(int i = 0; i < N; i++)
    {
       System.out.print(countLeftGreater[i] + " ");
    }
}
   
// Function to get the count of greater
// elements on left of each array element
static void countGreater(int arr[], int N)
{
     
    // Store distinct array
    // elements in sorted order
    Set<Integer> St = new TreeSet<>();
   
    // Stores the count of greater
    // elements on the left side
    int[] countLeftGreater = new int[N];
   
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Insert array elements
        // into the set
        St.add(arr[i]);
   
        int it = 0;
         
        // Find previous greater element
        Iterator<Integer> iterator = St.iterator();
        while (iterator.hasNext())
        {
           if (arr[i] < iterator.next())
           {
               break;
           }
           it++;
        }
   
        // Find the distance between the
        // previous greater element of arr[i]
        // and last element of the set
        countLeftGreater[i] = Math.abs(it - St.size());
    }
    display(countLeftGreater, N); 
}
 
// Driver code
public static void main (String[] args)
{
    int arr[] = { 12, 1, 2, 3, 0, 11, 4 };
    int N = arr.length;
     
    countGreater(arr, N);
}
}
 
// This code is contributed by offbeat

Python3




# Python3 program to implement
# the above approach
 
# Function to print the count of greater
# elements on left of each array element
def display(countLeftGreater, N):
     
    for i in range(N):
        print(countLeftGreater[i], end = " ")
 
# Function to get the count of greater
# elements on left of each array element
def countGreater(arr, N):
     
    # Store distinct array
    # elements in sorted order
    St = set()
 
    # Stores the count of greater
    # elements on the left side
    countLeftGreater = [0] * (N)
     
    # Traverse the array
    for i in range(N):
         
        # Insert array elements
        # into the set
        St.add(arr[i])
 
        it = 0
 
        # Find previous greater element
        for st in St:
            if (arr[i] < st):
                break
 
            it += 1
        # Find the distance between the
        # previous greater element of arr[i]
        # and last element of the set
        countLeftGreater[i] = abs(it - len(St))
 
    display(countLeftGreater, N)
 
# Driver code
if __name__ == '__main__':
     
    arr = [ 12, 1, 2, 3, 0, 11, 4 ]
    N = len(arr)
 
    countGreater(arr, N)
 
# This code is contributed by Rajput-Ji

C#




// C# program to implement
// the above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to print the count of greater
// elements on left of each array element
static void display(int []countLeftGreater, int N)
{
    for(int i = 0; i < N; i++)
    {
        Console.Write(countLeftGreater[i] + " ");
    }
}
   
// Function to get the count of greater
// elements on left of each array element
static void countGreater(int []arr, int N)
{
     
    // Store distinct array
    // elements in sorted order
    List<int> St = new List<int>();
   
    // Stores the count of greater
    // elements on the left side
    int[] countLeftGreater = new int[N];
   
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
         
        // Insert array elements
        // into the set
        St.Add(arr[i]);
   
        int it = 0;
        St.Sort();
         
        // Find previous greater element
        foreach(int itr in St)
        {
            if (arr[i] < itr)
            {
                break;
            }
            it++;
        }
         
        // Find the distance between the
        // previous greater element of arr[i]
        // and last element of the set
        countLeftGreater[i] = Math.Abs(it - St.Count);
    }
    display(countLeftGreater, N); 
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 12, 1, 2, 3, 0, 11, 4 };
    int N = arr.Length;
     
    countGreater(arr, N);
}
}
 
// This code is contributed by gauravrajput1

Javascript




<script>
// Js program to implement
// the above approach
 
// Function to print the count of greater
// elements on left of each array element
function display( countLeftGreater, N)
{
    for (let i = 0; i < N; i++) {
        document.write(countLeftGreater[i] ," ");
    }
}
 
// Function to get the count of greater
// elements on left of each array element
function countGreater(arr,  N)
{
    // Store distinct array
    // elements in sorted order
    let St = new Set();
 
    // Stores the count of greater
    // elements on the left side
    let countLeftGreater = [];
 
    // Traverse the array
    for (let i = 0; i < N; i++) {
 
        // Insert array elements
        // into the set
        St.add(arr[i]);
 
        // Find previous greater element
        let it = 0;
        // Find previous greater element
        //let a = Array.from(St);
        //a.sort(function(a,b){return a-b});
         
        for (let st of St){
            if (arr[i] < st)
            it += 1;
        }
        // Find the distance between the
        // previous greater element of arr[i]
        // and last element of the set
        countLeftGreater[i]
            = Math.abs(it);
    }
    display(countLeftGreater, N);
}
 
// Driver Code
let arr = [ 12, 1, 2, 3, 0, 11, 4 ];
let N = arr.length;
countGreater(arr, N);
</script>
Output: 
0 1 1 1 4 1 2

 

Time Complexity: O(N2) because distance function takes O(N) but the above implementation is very simple and works better than the naive algorithm in the average case. 
Auxiliary Space: O(N) 

Note: Above approach works for unique elements but for duplicate elements just replace Set with Multiset.

 

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :