![]() |
VOOZH | about |
Given an array of integers, A[] of size N. For each ith element in the array, calculate the absolute difference between the count of numbers that are to the left of i and are strictly greater than the ith element, and the count of numbers that are to the right of i and are strictly lesser than the ith element.
Examples:
Input: N = 5, A[] = {5, 4, 3, 2, 1}
Output: 4 2 0 2 4
Explanation: We can see that the required number for the 1st element is |0-4| = 4Input: N = 5, A[] = {1, 2, 3, 4, 5}
Output: 0 0 0 0 0
Explanation: There is no greater element on the left for any element and no lesser element on the right.
Approach: To solve the problem follow the below idea:
The solution to finding the absolute difference between the number of elements greater than and lesser than each element in a given array, involves using a Binary Index Tree. The approach involves sorting the array and mapping each element to its corresponding index in the sorted array, constructing two Binary Index Trees for counting the number of elements less than each element from the right side and greater than each element from the left side, respectively, and computing the absolute difference between the counts for each element.
Steps that were to follow the above approach:
Below is the code to implement the above steps:
[4, 2, 0, 2, 4]
Time Complexity: O(N * log N)
Auxiliary Space: O(N)