VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-based-absolute-difference-for-array-element/

⇱ Count-based Absolute difference for Array element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count-based Absolute difference for Array element

Last Updated : 15 Sep, 2023

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| = 4

Input: 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:

  • Create a Binary Index Tree object with an array of size n+1 initialized with 0.
  • Sort the given input array and create a map of the sorted array elements with their corresponding indices.
  • Create an array of indices of the input array elements using the map created in the previous step.
  • Create another Binary Index Tree object with an array of size n+1 initialized with 0.
  • Traverse the array of indices from right to left and for each index,  
    • find the number of elements smaller than the current element to its right using the Binary Index Tree created in the previous step, update the Binary Index Tree with the current index, and store the result in a separate array.
  • Reverse the array of indices and repeat the traversal, but this time find the number of elements greater than the current element to its left.
  • For each element in the two arrays created in the two traversals, calculate their absolute difference and store the result in a third array.
  • Return the third array as the final result.

Below is the code to implement the above steps:


Output
[4, 2, 0, 2, 4]

Time Complexity: O(N * log N)
Auxiliary Space: O(N)

Comment
Article Tags: