VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-surpasser-count-of-each-element-in-array/

⇱ Surpasser Count of Each Element in Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Surpasser Count of Each Element in Array

Last Updated : 14 Jul, 2025

Given an array of distinct integers arr[], a surpasser of an element arr[i] is any element arr[j] such that j > i and arr[j] > arr[i]. Find the number of surpassers for each element in the array.

Examples:

Input: arr[] = [2, 7, 5, 3, 8, 1]
Output: [4, 1, 1, 1, 0, 0]
Explanation: For 2, there are 4 greater elements to its right: [7, 5, 3, 8]
For 7, there is 1 greater element to its right: [8]
For 5, there is 1 greater element to its right: [8]
For 3, there is 1 greater element to its right: [8]
For 8, there is no greater element to its right: [0]
For 1, there is no greater element to its right: [0]

Input: arr[] = [4, 5, 1]
Output: [1, 0, 0]
Explanation: For 4, there is 1 greater element to its right: [5]
For 5, there is no greater element to its right: [0]
For 1, there is no greater element to its right: [0]

[Naive Approach] - Using Two Nested Loops - O(n^2) Time and O(1) Space

The simplest approach is to iterate through the array, and for each element count the number of elements to its right that is greater than it.


Output
4 1 1 1 0 0 

[Expected Approach] - Using Merge Step of Merge Sort - O(n Log n) Time and O(n) Space

In this approach, we use the merge step of merge sort. During the merge, if the ith element in the left half is smaller than the jth element in the right half, it means that all remaining elements in the right half (from j to end) are greater than the ith element in the left half (since both halves are sorted). Therefore, we add the number of remaining elements in the right half to the surpasser count of the ith element of the left half. This process is repeated for all elements in the left half as they are merged with the right half.

Since all the elements in the array are distinct, we use a hash map to keep store of the surpasser count for each element. After the merge sort is complete, we fill the result array with the surpasser counts, maintaining the same order as the original input.


Output
4 1 1 1 0 0 

Related Articles:

Comment
Article Tags: