![]() |
VOOZH | about |
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]
Table of Content
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.
4 1 1 1 0 0
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.
4 1 1 1 0 0
Related Articles: