![]() |
VOOZH | about |
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 that inversion count is the maximum.
Two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j. For simplicity, we may assume that all elements are unique.
Example:
Input: arr[] = {8, 4, 2, 1}
Output: 6
Explanation: Given array has six inversions: (8,4), (4,2), (8,2), (8,1), (4,1), (2,1).Input: arr[] = {3, 1, 2}
Output: 2
Explanation: Given array has two inversions: (3,1), (3,2).
We have already discussed the below methods to solve inversion count:
We recommend you to refer Binary Indexed Tree (BIT) before further reading this post.
Below is the implementation of the above approach:
Number of inversions are : 6
Time Complexity :- The update function and getSum function runs for O(log(maximumelement)). The getSum function has to be run for every element in the array. So overall time complexity is : O(nlog(maximumelement)).
Auxiliary space : O(maxElement), space required for the BIT is an array of the size of the largest element.
Θ
Approach: Traverse through the array and for every index find the number of smaller elements on its right side of the array. This can be done using BIT. Sum up the counts for all indexes in the array and print the sum. The approach remains the same but the problem with the previous approach is that it doesn't work for negative numbers as the index cannot be negative. The idea is to convert the given array to an array with values from 1 to n and the relative order of smaller and greater elements remains the same.
Example:
arr[] = {7, -90, 100, 1}
It gets converted to,
arr[] = {3, 1, 4 ,2 }
as -90 < 1 < 7 < 100.
Explanation: Make a BIT array of a number of
elements instead of a maximum element. Changing
element will not have any change in the answer
as the greater elements remain greater and at the
same position.
Algorithm:
Below is the implementation of the above approach:
Number of inversions are : 6
Time Complexity: The update function and getSum function runs for O(log(n)). The getSum function has to be run for every element in the array. So overall time complexity is O(nlog(n)).
Auxiliary Space: O(n).
Space required for the BIT is an array of the size n.