VOOZH about

URL: https://www.geeksforgeeks.org/dsa/inversion-count-in-array-using-self-balancing-bst/

⇱ Inversion count in Array Using Self-Balancing BST - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Inversion count in Array Using Self-Balancing BST

Last Updated : 23 Jul, 2025

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]
Output: 6
Explanation:

👁 inversion-count


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 < j

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

  • Time Complexity of the Naive approach is O(n2
  • Time Complexity of merge sort based approach is O(n Log n). 

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:

  1. Create an AVL tree, with a property that every node will contain the size of its subtree.
  2. Traverse the array from start to the end.
  3. For every element insert the element in the AVL tree.
  4. The count of the nodes which are greater than the current element can be found out by checking the size of the subtree of its right children, So it can be guaranteed that elements in the right subtree of current node have index less than the current element and their values are greater than the current element. So those elements satisfy the criteria.
  5. So increase the count by size of subtree of right child of the current inserted node.
  6. return the count.

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

Comment
Article Tags: