![]() |
VOOZH | about |
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:
Below is the implementation of the above approach:
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.
3 1 3 1 0 0
Time Complexity: O(N^2)
Auxiliary Space: O(N)