VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-larger-elements-on-right-side-of-each-element-in-an-array/

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


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 15 Jul, 2025

Given an arrayarr[] 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: 


Output
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. 


Output
3 1 3 1 0 0 

Time Complexity: O(N^2) 
Auxiliary Space: O(N)

Comment