Count of larger elements on right side of each element in an array

Given an array arr[] consisting of N integers, the task is to count the number of greater elements on the right side of each array element.
Examples:
Input: arr[] = {3, 7, 1, 5, 9, 2}Â
Output: {3, 1, 3, 1, 0, 0}Â
Explanation: For arr[0], the elements greater than it on the right are {7, 5, 9}. For arr[1], the only element greater than it on the right is {9}. For arr[2], the elements greater than it on the right are {5, 9, 2}. For arr[3], the only element greater than it on the right is {9}. For arr[4] and arr[5], no greater elements exist on the right.Input: arr[] = {5, 4, 3, 2}Â
Output: {0, 0, 0, 0}
Naive Approach: The simplest approach is to iterate all array elements using two loops and for each array element, count the number of elements greater than it on its right side and then print it.Â
Time Complexity: O(N2)Â
Auxiliary Space: O(1)
Efficient Approach: The problem can be solved using the concept of Merge Sort in descending order. Follow the steps given below to solve the problem:
- Initialize an array count[] where count[i] store the respective count of greater elements on the right for every arr[i]
- Take the indexes i and j, and compare the elements in an array.
- If higher index element is greater than the lower index element then, all the higher index element will be greater than all the elements after that lower index.
- Since the left part is already sorted, add the count of elements after the lower index element to the count[] array for the lower index.
- Repeat the above steps until the entire array is sorted.
- Finally print the values of count[] array.
Below is the implementation of the above approach:Â
Java
// Java program for the above approachÂ
import java.util.*;Â
public class GFG {Â
    // Stores the index & value pairs    static class Item {Â
        int val;        int index;Â
        public Item(int val, int index)        {            this.val = val;            this.index = index;        }    }Â
    // Function to count the number of    // greater elements on the right    // of every array element    public static ArrayList<Integer>    countLarge(int[] a)    {        // Length of the array        int len = a.length;Â
        // Stores the index-value pairs        Item[] items = new Item[len];Â
        for (int i = 0; i < len; i++) {            items[i] = new Item(a[i], i);        }Â
        // Stores the count of greater        // elements on right        int[] count = new int[len];Â
        // Perform MergeSort operation        mergeSort(items, 0, len - 1,                  count);Â
        ArrayList<Integer> res = new ArrayList<>();Â
        for (int i : count) {            res.add(i);        }Â
        return res;    }Â
    // Function to sort the array    // using Merge Sort    public static void mergeSort(        Item[] items, int low ,int high,        int[] count)    {Â
        // Base Case        if (low >= high) {            return;        }Â
        // Find Mid        int mid = low + (high - low) / 2;Â
        mergeSort(items, low, mid,                  count);        mergeSort(items, mid + 1,                  high, count);Â
        // Merging step        merge(items, low, mid,              mid + 1, high, count);    }Â
    // Utility function to merge sorted    // subarrays and find the count of    // greater elements on the right    public static void merge(        Item[] items, int low, int lowEnd,        int high, int highEnd, int[] count)    {        int m = highEnd - low + 1; // midÂ
        Item[] sorted = new Item[m];Â
        int rightCounter = 0;        int lowInd = low, highInd = high;        int index = 0;Â
        // Loop to store the count of        // larger elements on right side        // when both array have elements        while (lowInd <= lowEnd               && highInd <= highEnd) {Â
            if (items[lowInd].val                < items[highInd].val) {                rightCounter++;                sorted[index++]                    = items[highInd++];            }            else {                count[items[lowInd].index] += rightCounter;                sorted[index++] = items[lowInd++];            }        }Â
        // Loop to store the count of        // larger elements in right side        // when only left array have        // some element        while (lowInd <= lowEnd) {Â
            count[items[lowInd].index] += rightCounter;            sorted[index++] = items[lowInd++];        }Â
        // Loop to store the count of        // larger elements in right side        // when only right array have        // some element        while (highInd <= highEnd) {Â
            sorted[index++] = items[highInd++];        }Â
        System.arraycopy(sorted, 0, items,                         low, m);    }Â
    // Utility function that prints    // the count of greater elements    // on the right    public static void    printArray(ArrayList<Integer> countList)    {Â
        for (Integer i : countList)            System.out.print(i + " ");Â
        System.out.println();    }Â
    // Driver Code    public static void main(String[] args)    {        // Given array        int arr[] = { 3, 7, 1, 5, 9, 2 };        int n = arr.length;Â
        // Function Call        ArrayList<Integer> countList            = countLarge(arr);Â
        printArray(countList);    }} |
Python3
from typing import ListÂ
class Item:    def __init__(self, val: int, index: int):        self.val = val        self.index = indexÂ
def count_large(a: List[int]) -> List[int]:    # Length of the array    length = len(a)Â
    # Stores the index-value pairs    items = [Item(a[i], i) for i in range(length)]Â
    # Stores the count of greater elements on right    count = [0] * lengthÂ
    # Perform MergeSort operation    merge_sort(items, 0, length - 1, count)Â
    res = count.copy()Â
    return resÂ
def merge_sort(items: List[Item], low: int, high: int, count: List[int]) -> None:    # Base Case    if low >= high:        returnÂ
    # Find Mid    mid = low + (high - low) // 2Â
    merge_sort(items, low, mid, count)    merge_sort(items, mid + 1, high, count)Â
    # Merging step    merge(items, low, mid, mid + 1, high, count)Â
def merge(items: List[Item], low: int, low_end: int, high: int, high_end: int, count: List[int]) -> None:Â Â Â Â m = high_end - low + 1Â # midÂ
    sorted_items = [None] * mÂ
    right_counter = 0    low_ind = low    high_ind = high    index = 0Â
    # Loop to store the count of larger elements on right side    # when both array have elements    while low_ind <= low_end and high_ind <= high_end:        if items[low_ind].val < items[high_ind].val:            right_counter += 1            sorted_items[index] = items[high_ind]            index += 1            high_ind += 1        else:            count[items[low_ind].index] += right_counter            sorted_items[index] = items[low_ind]            index += 1            low_ind += 1Â
    # Loop to store the count of larger elements in right side    # when only left array have elements    while low_ind <= low_end:        count[items[low_ind].index] += right_counter        sorted_items[index] = items[low_ind]        index += 1        low_ind += 1Â
    # Loop to store the count of larger elements in right side    # when only right array have elements    while high_ind <= high_end:        sorted_items[index] = items[high_ind]        index += 1        high_ind += 1Â
    items[low:low + m] = sorted_itemsÂ
def print_array(count_list: List[int]) -> None:Â Â Â Â print(' '.join(str(i) for i in count_list))Â
# Driver Codeif __name__ == '__main__':    # Given array    arr = [3, 7, 1, 5, 9, 2]Â
    # Function Call    count_list = count_large(arr)Â
    print_array(count_list)Â
# This code is contributed by Aditya Sharma |
C#
using System;using System.Collections.Generic;Â
public class GFG {    // Stores the index & value pairs    public class Item {        public int val;        public int index;Â
        public Item(int val, int index)        {            this.val = val;            this.index = index;        }    }Â
    // Function to count the number of    // greater elements on the right    // of every array element    public static List<int> CountLarge(int[] a)    {        // Length of the array        int len = a.Length;Â
        // Stores the index-value pairs        Item[] items = new Item[len];Â
        for (int i = 0; i < len; i++) {            items[i] = new Item(a[i], i);        }Â
        // Stores the count of greater        // elements on right        int[] count = new int[len];Â
        // Perform MergeSort operation        MergeSort(items, 0, len - 1, count);Â
        List<int> res = new List<int>();Â
        foreach(int i in count) { res.Add(i); }Â
        return res;    }Â
    // Function to sort the array    // using Merge Sort    public static void MergeSort(Item[] items, int low,                                 int high, int[] count)    {        // Base Case        if (low >= high) {            return;        }Â
        // Find Mid        int mid = low + (high - low) / 2;Â
        MergeSort(items, low, mid, count);        MergeSort(items, mid + 1, high, count);Â
        // Merging step        Merge(items, low, mid, mid + 1, high, count);    }Â
    // Utility function to merge sorted    // subarrays and find the count of    // greater elements on the right    public static void Merge(Item[] items, int low,                             int lowEnd, int high,                             int highEnd, int[] count)    {        int m = highEnd - low + 1; // midÂ
        Item[] sorted = new Item[m];Â
        int rightCounter = 0;        int lowInd = low, highInd = high;        int index = 0;Â
        // Loop to store the count of        // larger elements on right side        // when both array have elements        while (lowInd <= lowEnd && highInd <= highEnd) {            if (items[lowInd].val < items[highInd].val) {                rightCounter++;                sorted[index++] = items[highInd++];            }            else {                count[items[lowInd].index] += rightCounter;                sorted[index++] = items[lowInd++];            }        }Â
        // Loop to store the count of        // larger elements in right side        // when only left array have        // some element        while (lowInd <= lowEnd) {            count[items[lowInd].index] += rightCounter;            sorted[index++] = items[lowInd++];        }Â
        // Loop to store the count of        // larger elements in right side        // when only right array have        // some element        while (highInd <= highEnd) {            sorted[index++] = items[highInd++];        }Â
        Array.Copy(sorted, 0, items, low, m);    }Â
    // Utility function that prints    // the count of greater elements    // on the right    public static void PrintArray(List<int> countList)    {        foreach(int i in countList)        {            Console.Write(i + " ");        }        Console.WriteLine();    }Â
    // Driver Code    public static void Main(string[] args)    {        // Given array        int[] arr = { 3, 7, 1, 5, 9, 2 };        int n = arr.Length;Â
        // Function Call        List<int> countList = CountLarge(arr);Â
        PrintArray(countList);    }}// This code is contributed by akashish__ |
Javascript
//Javascript equivalentÂ
//Define an object Itemclass Item {  constructor(val, index) {    this.val = val    this.index = index  }}Â
//Function to count large elementsfunction countLarge(arr) {  // Length of the array  const length = arr.lengthÂ
  // Stores the index-value pairs  const items = []  for (let i = 0; i < length; i++) {    items.push(new Item(arr[i], i))  }Â
  // Stores the count of greater elements on right  const count = []  for (let i = 0; i < length; i++) {    count.push(0)  }Â
  // Perform MergeSort operation  mergeSort(items, 0, length - 1, count)Â
  const res = count.slice(0)Â
  return res}Â
//Merge Sort functionfunction mergeSort(items, low, high, count) {  // Base Case  if (low >= high) returnÂ
  // Find Mid  const mid = low + Math.floor((high - low) / 2)Â
  mergeSort(items, low, mid, count)  mergeSort(items, mid + 1, high, count)Â
  // Merging step  merge(items, low, mid, mid + 1, high, count)}Â
//Merge functionfunction merge(items, low, lowEnd, high, highEnd, count) {Â Â const mid = highEnd - low + 1 // midÂ
  const sortedItems = []  for (let i = 0; i < mid; i++) {    sortedItems.push(null)  }Â
  let rightCounter = 0  let lowInd = low  let highInd = high  let index = 0Â
  // Loop to store the count of larger elements on right side  // when both array have elements  while (lowInd <= lowEnd && highInd <= highEnd) {    if (items[lowInd].val < items[highInd].val) {      rightCounter++      sortedItems[index] = items[highInd]      index++      highInd++    } else {      count[items[lowInd].index] += rightCounter      sortedItems[index] = items[lowInd]      index++      lowInd++    }  }Â
  // Loop to store the count of larger elements in right side  // when only left array have elements  while (lowInd <= lowEnd) {    count[items[lowInd].index] += rightCounter    sortedItems[index] = items[lowInd]    index++    lowInd++  }Â
  // Loop to store the count of larger elements in right side  // when only right array have elements  while (highInd <= highEnd) {    sortedItems[index] = items[highInd]    index++    highInd++  }Â
  for (let i = 0; i < mid; i++) {    items[low + i] = sortedItems[i]  }}Â
//Function to print arrayfunction printArray(countList) {Â Â let str = ''Â Â for (let i = 0; i < countList.length; i++) {Â Â Â Â str += countList[i] + ' 'Â Â }Â Â console.log(str)}Â
// Driver Code  // Given array  const arr = [3, 7, 1, 5, 9, 2]Â
  // Function Call  const countList = countLarge(arr)Â
  printArray(countList) |
3 1 3 1 0 0
Time Complexity: O(N*log N)Â
Auxiliary Space: O(N)
Another approach: We can use binary search to solve this. The idea is to create a sorted list of input and then for each element of input we first remove that element from the sorted list and then apply the modified binary search to find the element just greater than the current element and then the number of large elements will be the difference between the found index & the length of sorted list.Â
C++
#include <iostream>#include <algorithm>#include <vector>using namespace std;Â
// Helper function to count the number of elements greater than 'item' in the sorted 'list'int CountLargeNumbers(int item, vector<int>& list) {Â Â Â Â int l=0;Â Â Â Â int r=list.size()-1;Â Â Â Â int mid = 0;Â Â Â Â while(l<r){Â Â Â Â Â Â Â Â mid = l + (r-l)/2;Â Â Â Â Â Â Â Â if(list[mid] > item){Â Â Â Â Â Â Â Â Â Â Â Â r = mid;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â else{Â Â Â Â Â Â Â Â Â Â Â Â l = mid + 1;Â Â Â Â Â Â Â Â }Â Â Â Â }Â Â Â Â if(l==r && item > list[l]){Â Â Â Â Â Â Â Â return 0;Â Â Â Â }Â Â Â Â return list.size()-l;}Â
// Helper function to delete the first occurrence of 'item' from the sorted 'list'void DeleteItemFromSortedList(vector<int>& list, int item) {Â Â Â Â int index = lower_bound(list.begin(), list.end(), item) - list.begin();Â Â Â Â list.erase(list.begin() + index);}Â
// Function to count the number of elements greater than each element in the input list 'list'vector<int> CountLarge(vector<int>& list) {    // Create a sorted copy of the input list    vector<int> sortedList = list;    sort(sortedList.begin(), sortedList.end());Â
    // For each element in the input list, count the number of elements greater than it    for (int i = 0; i < list.size(); i++) {        DeleteItemFromSortedList(sortedList, list[i]);        list[i] = CountLargeNumbers(list[i], sortedList);    }    return list;}Â
// Helper function to print the contents of a vectorvoid PrintArray(vector<int>& list) {Â Â Â Â for (int i = 0; i < list.size(); i++) {Â Â Â Â Â Â Â Â cout << list[i] << " ";Â Â Â Â }Â Â Â Â cout << endl;}Â
// Main functionint main() {    // Create an input vector    vector<int> arr = {3, 7, 1, 5, 9, 2};Â
    // Call the 'CountLarge' function to count the number of elements greater than each element in 'arr'    vector<int> res = CountLarge(arr);Â
    // Print the result vector    PrintArray(res);Â
    return 0;} |
Java
import java.util.*;Â
public class Main {Â Â Â Â // Helper function to count the number of elements greater than 'item' in the sorted 'list'Â Â Â Â public static int countLargeNumbers(int item, List<Integer> list) {Â Â Â Â Â Â Â Â int l = 0;Â Â Â Â Â Â Â Â int r = list.size() - 1;Â Â Â Â Â Â Â Â int mid = 0;Â Â Â Â Â Â Â Â while (l < r) {Â Â Â Â Â Â Â Â Â Â Â Â mid = l + (r - l) / 2;Â Â Â Â Â Â Â Â Â Â Â Â if (list.get(mid) > item) {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â r = mid;Â Â Â Â Â Â Â Â Â Â Â Â } else {Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â l = mid + 1;Â Â Â Â Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â if (l == r && item > list.get(l)) {Â Â Â Â Â Â Â Â Â Â Â Â return 0;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â return list.size() - l;Â Â Â Â }Â
    // Helper function to delete the first occurrence of 'item' from the sorted 'list'    public static void deleteItemFromSortedList(List<Integer> list, int item) {        int index = Collections.binarySearch(list, item);        if (index >= 0) {            list.remove(index);        }    }Â
    // Function to count the number of elements greater than each element in the input list 'list'    public static List<Integer> countLarge(List<Integer> list) {        // Create a sorted copy of the input list        List<Integer> sortedList = new ArrayList<>(list);        Collections.sort(sortedList);Â
        // For each element in the input list, count the number of elements greater than it        for (int i = 0; i < list.size(); i++) {            deleteItemFromSortedList(sortedList, list.get(i));            list.set(i, countLargeNumbers(list.get(i), sortedList));        }        return list;    }Â
    // Helper function to print the contents of a list    public static void printList(List<Integer> list) {        for (int i = 0; i < list.size(); i++) {            System.out.print(list.get(i) + " ");        }        System.out.println();    }Â
    // Main function    public static void main(String[] args) {        // Create an input list        List<Integer> arr = new ArrayList<>(Arrays.asList(3, 7, 1, 5, 9, 2));Â
        // Call the 'countLarge' function to count the number of elements greater than each element in 'arr'        List<Integer> res = countLarge(arr);Â
        // Print the result list        printList(res);    }} |
Python3
def CountLarge(list):Â Â Â Â sortedList = sorted(list)Â Â Â Â for i in range(len(list)):Â Â Â Â Â Â Â Â DeleteItemFromSortedList(sortedList, list[i])Â Â Â Â Â Â Â Â list[i] = CountLargeNumbers(list[i], sortedList)Â Â Â Â return listÂ
def CountLargeNumbers(item, list):    l=0    r=len(list)-1    mid = 0    while(l<r):        mid = l + (r-l)//2        if(list[mid] > item):            r = mid        else:            l = mid + 1    if(l==r and item > list[l]):        return 0    return len(list)-lÂ
def DeleteItemFromSortedList(list, item):Â Â Â Â index = BinarySearch(list, item)Â Â Â Â list.pop(index)Â
def BinarySearch(list, item):    l=0    r=len(list)-1    mid = 0    while(l<=r):        mid = l + (r-l)//2        if(list[mid] == item):            return mid        elif(list[mid] < item):            l = mid + 1        else:            r = mid - 1    return -1Â
def PrintArray(list):Â Â Â Â for item in list:Â Â Â Â Â Â Â Â print(item, end=" ")Â
arr = [3, 7, 1, 5, 9, 2]Â
res = CountLarge(arr)Â
PrintArray(res) |
C#
using System;using System.Collections.Generic;Â
public class GFG{    static public void Main (){        //Code          var arr = new List<int>(){3, 7, 1, 5, 9, 2};        var res = CountLarge(arr);        PrintArray(res);    }    public static List<int> CountLarge(List<int> list)    {        var sortedList = new List<int>(list);        sortedList.Sort();        for(int i=0;i<list.Count;i++){            DeleteItemFromSortedList(sortedList, list[i]);            list[i] = CountLargeNumbers(list[i], sortedList);        }        return list;    }    public static int CountLargeNumbers(int item, List<int> list){        int l=0,r=list.Count-1,mid;        while(l<r){            mid = l + (r-l)/2;            if(list[mid] > item)                r = mid;            else                l = mid + 1;        }        if(l==r && item > list[l])            return 0;        return list.Count-l;    }    public static void DeleteItemFromSortedList(List<int> list, int item){        var index = BinarySearch(list, item);        list.RemoveAt(index);    }    public static int BinarySearch(List<int> list, int item){        int l=0,r=list.Count-1,mid;        while(l<=r){            mid = l + (r-l)/2;            if(list[mid] == item)                return mid;            else if(list[mid] < item)                l = mid + 1;            else                r = mid - 1;        }        return -1;    }    public static void PrintArray(List<int> list)    {        foreach(var item in list)            Console.Write(item + " ");    }} |
Javascript
<script>function main() {  //Code  const arr = [3, 7, 1, 5, 9, 2];  const res = countLarge(arr);  printArray(res);}Â
function countLarge(list) {Â Â const sortedList = [...list];Â Â sortedList.sort();Â Â for (let i = 0; i < list.length; i++) {Â Â Â Â deleteItemFromSortedList(sortedList, list[i]);Â Â Â Â list[i] = countLargeNumbers(list[i], sortedList);Â Â }Â Â return list;}Â
function countLargeNumbers(item, list) {Â Â let l = 0;Â Â let r = list.length - 1;Â Â let mid;Â Â while (l < r) {Â Â Â Â mid = l + Math.floor((r - l) / 2);Â Â Â Â if (list[mid] > item) r = mid;Â Â Â Â else l = mid + 1;Â Â }Â Â if (l === r && item > list[l]) return 0;Â Â return list.length - l;}Â
function deleteItemFromSortedList(list, item) {Â Â const index = binarySearch(list, item);Â Â list.splice(index, 1);}Â
function binarySearch(list, item) {Â Â let l = 0;Â Â let r = list.length - 1;Â Â let mid;Â Â while (l <= r) {Â Â Â Â mid = l + Math.floor((r - l) / 2);Â Â Â Â if (list[mid] === item) return mid;Â Â Â Â else if (list[mid] < item) l = mid + 1;Â Â Â Â else r = mid - 1;Â Â }Â Â return -1;}Â
function printArray(list) {Â Â for (const item of list) {Â Â Â Â document.write(item + " ");Â Â }}Â
main();Â
</script> |
3 1 3 1 0 0
Time Complexity: O(N^2)Â
Auxiliary Space: O(N)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



