Open In App

Count greater elements on the left side of every array element

Last Updated : 13 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

  • Create an empty Set, St.
  • Traverse the array and insert every element in St one by one.
  • Find the previous greater element of arr[i] using upper_bound function.
  • Find the distance between the previous greater element and the last element of the set using the distance function.
  • Store the distance in the array, countLeftGreater[].
  • 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.



Similar Reads

Count smaller elements on right side and greater elements on left side using Binary Index Tree
Given an array arr[] of size N. The task is to find smaller elements on the right side and greater elements on the left side for each element arr[i] in the given array. Examples: Input: arr[] = {12, 1, 2, 3, 0, 11, 4} Output: Smaller right: 6 1 1 1 0 1 0 Greater left: 0 1 1 1 4 1 2 Input: arr[] = {5, 4, 3, 2, 1} Output: Smaller right: 4 3 2 1 0 Gre
16 min read
Closest greater or same value on left side for every element in array
Given an array of integers, find the closest (not considering the distance, but value) greater or the same value on the left of every element. If an element has no greater or same value on the left side, print -1. Examples: Input : arr[] = {10, 5, 11, 6, 20, 12} Output : -1, 10, -1, 10, -1, 20 The first element has nothing on the left side, so the
8 min read
Partition array into two subarrays with every element in the right subarray strictly greater than every element in left subarray
Given an array arr[] consisting of N integers, the task is to partition the array into two non-empty subarrays such that every element present in the right subarray is strictly greater than every element present in the left subarray. If it is possible to do so, then print the two resultant subarrays. Otherwise, print "Impossible". Examples: Input:
12 min read
Print greater elements present on the left side of each array element
Given an array arr[] consisting of N distinct integers, the task is to print for each array element, all the greater elements present on its left. Examples: Input: arr[] = {5, 3, 9, 0, 16, 12}Output:5: 3: 59: 0: 9 5 316: 12: 16 Input: arr[] = {1, 2, 0}Output:1: 2: 0: 2 1 Naive Approach: The simplest approach to solve the problem is to traverse the
10 min read
Replace every element with the greatest element on its left side
Given an array of integers, the task is to replace every element with the greatest element on its left side. Note: Replace the first element with -1 as it has no element in its left. Examples: Input: arr[] = {4, 5, 2, 1, 7, 6}Output: -1 4 5 5 5 7Explanation:Since, 4 has no element in its left, so replace it by -1.For 5, 4 is the greatest element in
6 min read
Replace every element with the smallest element on its left side
Given an array of integers, the task is to replace every element with the smallest element on its left side. Note: Replace the first element with -1 as it has no element in its left. Examples: Input: arr[] = {4, 5, 2, 1, 7, 6} Output: -1 4 4 2 1 1 Since, 4 has no element in its left, so replace it by -1. For 5, 4 is the smallest element in its left
7 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
Count array elements having at least one smaller element on its left and right side
Given an array arr[] of length N, the task is to find the number of elements in array arr[] which contains at least one smaller element on its left and right. Examples: Input: arr[] = {3, 9, 4, 6, 7, 5}Output: 3Explanation: Following 3 array elements satisfy the necessary conditions: arr[1] (= 9) has smaller element on left as 3 and on the right as
6 min read
Count the number of elements which are greater than any of element on right side of an array
Given an array Arr[]. The task is to count the number of elements Arr[i] in the given array such that one or more smaller elements are present on the right side of the element Arr[i] in array. Examples: Input: Arr[] = { 3, 9, 4, 6, 7, 5 } Output: 3Numbers that counts are: 9, 6, 7 9 - As all numbers are present after 9 are smaller than 9, 6 - 5 is s
4 min read
Count of Array elements greater than all elements on its left and next K elements on its right
Given an array arr[], the task is to print the number of elements which are greater than all the elements on its left as well as greater than the next K elements on its right. Examples: Input: arr[] = { 4, 2, 3, 6, 4, 3, 2}, K = 2 Output: 2 Explanation: arr[0](= 4): arr[0] is the 1st element in the array and greater than its next K(= 2) elements {2
14 min read
Article Tags :
Practice Tags :