Sunday, November 17, 2024
Google search engine
HomeData Modelling & AICount of greater elements for each element in the Array

Count of greater elements for each element in the Array

Given an array arr of integers of size N, the task is to find, for every element, the number of elements that are greater than it.
Examples: 
 

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

 

Approach: Store the frequencies of every array element using a Map. Iterate the Map in reverse and store the sum of the frequency of all previously traversed elements (i.e. elements greater than it) for every element.
Below code is the implementation of the above approach:
 

C++




// C++ implementation of the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
void countOfGreaterElements(int arr[], int n)
{
    // Store the frequency of the
    // array elements
    map<int, int> mp;
    for (int i = 0; i < n; i++) {
        mp[arr[i]]++;
    }
 
    int x = 0;
    // Store the sum of frequency of elements
    // greater than the current element
    for (auto it = mp.rbegin(); it != mp.rend(); it++) {
        int temp = it->second;
        mp[it->first] = x;
        x += temp;
    }
 
    for (int i = 0; i < n; i++)
        cout << mp[arr[i]] << " ";
}
 
// Driver code
int main()
{
 
    int arr[] = { 7, 9, 5, 2, 1, 3, 4, 8, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    countOfGreaterElements(arr, n);
 
    return 0;
}


Java




// Java implementation of the above approach
import java.util.*;
 
class GfG {
    public static void countOfGreaterElements(int arr[])
    {
        int n = arr.length;
 
        TreeMap<Integer, Integer> mp = new TreeMap<Integer, Integer>(Collections.reverseOrder());
 
        // Store the frequency of the
        // array elements
        for (int i = 0; i < n; i++) {
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
 
        // Store the sum of frequency of elements
        // greater than the current element
        int x = 0;
        for (Map.Entry<Integer, Integer> e : mp.entrySet()) {
            Integer temp = e.getValue();
            mp.put(e.getKey(), x);
            x += temp;
        }
 
        for (int i = 0; i < n; i++)
            System.out.print(mp.get(arr[i]) + " ");
    }
 
    public static void main(String args[])
    {
        int arr[] = { 7, 9, 5, 2, 1, 3, 4, 8, 6 };
        countOfGreaterElements(arr);
    }
}


Python 3




# Python 3 implementation of the above approach
 
def countOfGreaterElements(arr, n):
    # Store the frequency of the
    # array elements
    mp = {i:0 for i in range(1000)}
    for i in range(n):
        mp[arr[i]] += 1
 
    x = 0
    # Store the sum of frequency of elements
    # greater than the current element
    p = []
    q = []
    m = []
    for key, value in mp.items():
        m.append([key, value])
    m = m[::-1]
     
    for p in m:
        temp = p[1]
        mp[p[0]] = x
        x += temp
 
    for i in range(n):
        print(mp[arr[i]], end = " ")
 
# Driver code
if __name__ == '__main__':
    arr = [7, 9, 5, 2, 1, 3, 4, 8, 6]
    n = len(arr)
 
    countOfGreaterElements(arr, n)
 
# This code is contributed by Surendra_Gangwar


C#




// C# implementation of the above approach
 
using System;
using System.Collections.Generic;
 
 
class GfG {
    public static void countOfGreaterElements(int[] arr)
    {
        int n = arr.Length;
         
        SortedDictionary<int, int> mp =
          new SortedDictionary<int, int>();
 
        // Store the frequency of the
        // array elements
        for (int i = 0; i < n; i++) {
            int temp = 0;
            if (mp.ContainsKey(arr[i]))
            {
                temp = mp[arr[i]];
                mp.Remove(arr[i]);
            }
            mp[arr[i]] = temp + 1;
        }
 
        // Store the sum of frequency of elements
        // greater than the current element
        int x = 0;
         
        var k1 = mp.Keys;
         
        int[] keys = new int[mp.Count];
         
        k1.CopyTo(keys, 0);   
        Array.Reverse(keys);
         
         
        foreach (var e in keys) {
            int temp = mp[e];
             
            mp.Remove(e);
            mp[e] = x;
 
            x += temp;
        }
 
        for (int i = 0; i < n; i++)
            Console.Write(mp[arr[i]] + " ");
    }
 
    public static void Main(string[] args)
    {
        int[] arr = { 7, 9, 5, 2, 1, 3, 4, 8, 6 };
        countOfGreaterElements(arr);
    }
}
 
// This code is contributed by phasing17


Javascript




// JavaScript implementation of the above approach
 
function countOfGreaterElements(arr, n)
{
    // Store the frequency of the
    // array elements
    let mp = {}
     
     
    for (var i = 0; i < n; i++)
    {
        if (!mp.hasOwnProperty(arr[i]))
            mp[arr[i]] = 0
        mp[arr[i]] = mp[arr[i]] + 1
    }
     
    let x = 0
    // Store the sum of frequency of elements
    // greater than the current element
    let m = []
    for (var [key, value] of Object.entries(mp))
    {
 
        key = parseInt(key)
        value = parseInt(value)
        m.push([key, value])
    }
         
     
    for (var i = m.length - 1; i >= 0; i--)
    {
        var p = m[i]
        var temp = p[1]
        mp[p[0]] = x
        x += temp
    }
     
    for (var i = 0; i < n; i++)
        process.stdout.write(mp[arr[i]] + " ")
}
 
 
// Driver code
let arr = [7, 9, 5, 2, 1, 3, 4, 8, 6]
let n = arr.length
 
countOfGreaterElements(arr, n)
 
// This code is contributed by phasing17


Output: 

2 0 4 7 8 6 5 1 3

 

Time Complexity: O(N log(N))

Auxiliary Space: O(N)
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments