![]() |
VOOZH | about |
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.
Note: The 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, but if the array is sorted in reverse order, the inversion count is maximum.
Examples:
Input: arr[] = [4, 3, 2, 1]
👁 inversion-count
Output: 6
Explanation:
Input: arr[] = [1, 2, 3, 4, 5]
Output: 0
Explanation: There is no pair of indexes (i, j) exists in the given array such that arr[i] > arr[j] and i < jInput: arr[] = [10, 10, 10]
Output: 0
We have already discussed Naive approach and Merge Sort based approaches for counting inversions.
Complexity Analysis of solution in above mentioned post:
Prerequisute: Please go through AVL tree before reading this article.
Approach:
The idea is to use Self-Balancing Binary Search Tree like Red-Black Tree, AVL Tree, etc and augment it so that every node also keeps track of number of nodes in the right subtree. So every node will contain the count of nodes in its right subtree i.e. the number of nodes greater than that number. So it can be seen that the count increases when there is a pair (a,b), where a appears before b in the array and a > b, So as the array is traversed from start to the end, add the elements to the AVL tree and the count of the nodes in its right subtree of the newly inserted node will be the count increased or the number of pairs (a,b) where b is the present element.
Algorithm:
6
Time Complexity: O(n Log n), Insertion in an AVL insert takes O(log n) time and n elements are inserted in the tree
Auxiliary Space: O(n), To create a AVL tree with max n nodes O(n) extra space is required.
Related articles: