Open In App

Inversion Count using Policy Based Data Structure

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
4 Likes
Like
Report

Pre-requisite: Policy based data structure Given an array arr[], the task is to find the number of inversions for each element of the array.

Inversion Count: for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0. If the array is sorted in the reverse order then the inversion count is the maximum. Formally, Number of indices i   i   and j   j   such that arr[i]>arr[j]   arr[i] > arr[j]   and i<j   i < j   .

Examples:

Input: {5, 2, 3, 2, 3, 8, 1} Output: {0, 1, 1, 2, 1, 0, 6} Explanation: Inversion count for each elements - Element at index 0: There are no elements with less index than 0, which is greater than arr[0]. Element at index 1: There is one element with less index than 1, which is greater than 2. That is 5. Element at index 2: There is one element with less index than 2, which is greater than 3. That is 5. Element at index 3: There are two elements with less index than 3, which is greater than 2. That is 5, 3. Element at index 4: There is one element with less index than 4, which is greater than 3. That is 5. Element at index 5: There are no elements with less index than 5, which is greater than 8. Element at index 6: There are six elements with less index than 6, which is greater than 1. That is 5, 2, 3, 2, 3 Input: arr[] = {3, 2, 1} Output: {0, 1, 2}

Approach:

  • Create a policy based data structure of type pair.
  • Iterate the given array and perform the following steps -
    • Apply order_of_key({X, N+1}) for each element X where N is the size of array. Note: order_of_key is nothing but lower_bound. Also, we used N+1 because it is greater than all the indices in the array.
    • Let order_of_key comes out to be l, then the inversion count for current element will be equal to St.size()l   St.size() - l   which is ultimately the count of elements smaller than X and came before X in the array.
    • Insert the current element X along with its index in the policy-based data structure St. The index is inserted along with each element for its unique identification in the set and to deal with duplicates.

Below is the implementation of the above approach: 

C++
Java Python3 C# JavaScript

Output
0 1 1 2 1 0 6

Time Complexity: O(NLogN)O(N*LogN)


Next Article

Similar Reads