# Count inversions in an array | Set 2 (Using Self-Balancing BST)

Inversion Count for an array indicates – how far (or close) the array is from being sorted. If an array is already sorted then the inversion count is 0. If an 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 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).
There is one more efficient approach to solve the problem.

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. Display the count.

Implementation:

## C++

 `// An AVL Tree based C++ program to count  ` `// inversion in an array ` `#include ` `using` `namespace` `std; ` ` `  `// An AVL tree node ` `struct` `Node ` `{ ` `    ``int` `key, height; ` `    ``struct` `Node *left, *right; ` ` `  `// size of the tree rooted with this Node ` `    ``int` `size;  ` `}; ` ` `  `// A utility function to get the height of ` `// the tree rooted with N ` `int` `height(``struct` `Node *N) ` `{ ` `    ``if` `(N == NULL) ` `        ``return` `0; ` `    ``return` `N->height; ` `} ` ` `  `// A utility function to size of the ` `// tree of rooted with N ` `int` `size(``struct` `Node *N) ` `{ ` `    ``if` `(N == NULL) ` `        ``return` `0; ` `    ``return` `N->size; ` `} ` ` `  `/* Helper function that allocates a new Node with ` `the given key and NULL left and right pointers. */` `struct` `Node* newNode(``int` `key) ` `{ ` `    ``struct` `Node* node = ``new` `Node; ` `    ``node->key   = key; ` `    ``node->left   = node->right  = NULL; ` `    ``node->height = node->size = 1; ` `    ``return``(node); ` `} ` ` `  `// A utility function to right rotate  ` `// subtree rooted with y ` `struct` `Node *rightRotate(``struct` `Node *y) ` `{ ` `    ``struct` `Node *x = y->left; ` `    ``struct` `Node *T2 = x->right; ` ` `  `    ``// Perform rotation ` `    ``x->right = y; ` `    ``y->left = T2; ` ` `  `    ``// Update heights ` `    ``y->height = max(height(y->left), ` ` ``height(y->right))+1; ` `    ``x->height = max(height(x->left), ` ` ``height(x->right))+1; ` ` `  `    ``// Update sizes ` `    ``y->size = size(y->left) + size(y->right) + 1; ` `    ``x->size = size(x->left) + size(x->right) + 1; ` ` `  `    ``// Return new root ` `    ``return` `x; ` `} ` ` `  `// A utility function to left rotate  ` `// subtree rooted with x ` `struct` `Node *leftRotate(``struct` `Node *x) ` `{ ` `    ``struct` `Node *y = x->right; ` `    ``struct` `Node *T2 = y->left; ` ` `  `    ``// Perform rotation ` `    ``y->left = x; ` `    ``x->right = T2; ` ` `  `    ``//  Update heights ` `    ``x->height = max(height(x->left), height(x->right))+1; ` `    ``y->height = max(height(y->left), height(y->right))+1; ` ` `  `    ``// Update sizes ` `    ``x->size = size(x->left) + size(x->right) + 1; ` `    ``y->size = size(y->left) + size(y->right) + 1; ` ` `  `    ``// Return new root ` `    ``return` `y; ` `} ` ` `  `// Get Balance factor of Node N ` `int` `getBalance(``struct` `Node *N) ` `{ ` `    ``if` `(N == NULL) ` `        ``return` `0; ` `    ``return` `height(N->left) - height(N->right); ` `} ` ` `  `// Inserts a new key to the tree rotted with Node. Also, updates ` `// *result (inversion count) ` `struct` `Node* insert(``struct` `Node* node, ``int` `key, ``int` `*result) ` `{ ` `    ``/* 1.  Perform the normal BST rotation */` `    ``if` `(node == NULL) ` `        ``return``(newNode(key)); ` ` `  `    ``if` `(key < node->key) ` `    ``{ ` `        ``node->left  = insert(node->left, key, result); ` ` `  `        ``// UPDATE COUNT OF GREATE ELEMENTS FOR KEY ` `        ``*result = *result + size(node->right) + 1; ` `    ``} ` `    ``else` `        ``node->right = insert(node->right, key, result); ` ` `  `    ``/* 2. Update height and size of this ancestor node */` `    ``node->height = max(height(node->left), ` `                       ``height(node->right)) + 1; ` `    ``node->size = size(node->left) + size(node->right) + 1; ` ` `  `    ``/* 3. Get the balance factor of this ancestor node to ` `          ``check whether this node became unbalanced */` `    ``int` `balance = getBalance(node); ` ` `  `    ``// If this node becomes unbalanced, then there are ` `    ``// 4 cases ` ` `  `    ``// Left Left Case ` `    ``if` `(balance > 1 && key < node->left->key) ` `        ``return` `rightRotate(node); ` ` `  `    ``// Right Right Case ` `    ``if` `(balance < -1 && key > node->right->key) ` `        ``return` `leftRotate(node); ` ` `  `    ``// Left Right Case ` `    ``if` `(balance > 1 && key > node->left->key) ` `    ``{ ` `        ``node->left =  leftRotate(node->left); ` `        ``return` `rightRotate(node); ` `    ``} ` ` `  `    ``// Right Left Case ` `    ``if` `(balance < -1 && key < node->right->key) ` `    ``{ ` `        ``node->right = rightRotate(node->right); ` `        ``return` `leftRotate(node); ` `    ``} ` ` `  `    ``/* return the (unchanged) node pointer */` `    ``return` `node; ` `} ` ` `  `// The following function returns inversion count in arr[] ` `int` `getInvCount(``int` `arr[], ``int` `n) ` `{ ` `  ``struct` `Node *root = NULL;  ``// Create empty AVL Tree ` ` `  `  ``int` `result = 0;   ``// Initialize result ` ` `  `  ``// Starting from first element, insert all elements one by ` `  ``// one in an AVL tree. ` `  ``for` `(``int` `i=0; i

## Java

 `// AVL Tree based Java program to count ` `// inversion in an array ` `import` `java.util.*; ` ` `  `class` `GfG{ ` ` `  `// Initialize result ` `static` `int` `result = ``0``;  ` ` `  `// An AVL tree node ` `static` `class` `Node ` `{ ` `    ``int` `key, height; ` `    ``Node left, right; ` ` `  `    ``// Size of the tree rooted ` `    ``// with this Node ` `    ``int` `size; ` `} ` ` `  `// A utility function to get the height of ` `// the tree rooted with N ` `static` `int` `height(Node N) ` `{ ` `    ``if` `(N == ``null``) ` `        ``return` `0``; ` `         `  `    ``return` `N.height; ` `} ` ` `  `// A utility function to size of the ` `// tree of rooted with N ` `static` `int` `size(Node N) ` `{ ` `    ``if` `(N == ``null``) ` `        ``return` `0``; ` `         `  `    ``return` `N.size; ` `} ` ` `  `// A utility function to create a new node ` `static` `Node newNode(``int` `ele) ` `{ ` `    ``Node temp = ``new` `Node(); ` `    ``temp.key = ele; ` `    ``temp.left = ``null``; ` `    ``temp.right = ``null``; ` `    ``temp.height = ``1``; ` `    ``temp.size = ``1``; ` `    ``return` `temp; ` `} ` ` `  `// A utility function to right rotate ` `// subtree rooted with y ` `static` `Node rightRotate(Node y) ` `{ ` `    ``Node x = y.left; ` `    ``Node T2 = x.right; ` ` `  `    ``// Perform rotation ` `    ``x.right = y; ` `    ``y.left = T2; ` ` `  `    ``// Update heights ` `    ``y.height = Math.max(height(y.left),  ` `                        ``height(y.right)) + ``1``; ` `    ``x.height = Math.max(height(x.left), ` `                        ``height(x.right)) + ``1``; ` ` `  `    ``// Update sizes ` `    ``y.size = size(y.left) + size(y.right) + ``1``; ` `    ``x.size = size(x.left) + size(x.right) + ``1``; ` ` `  `    ``// Return new root ` `    ``return` `x; ` `} ` ` `  `// A utility function to left rotate ` `// subtree rooted with x ` `static` `Node leftRotate(Node x) ` `{ ` `    ``Node y = x.right; ` `    ``Node T2 = y.left; ` ` `  `    ``// Perform rotation ` `    ``y.left = x; ` `    ``x.right = T2; ` ` `  `    ``// Update heights ` `    ``x.height = Math.max(height(x.left),  ` `                        ``height(x.right)) + ``1``; ` `    ``y.height = Math.max(height(y.left), ` `                        ``height(y.right)) + ``1``; ` ` `  `    ``// Update sizes ` `    ``x.size = size(x.left) + size(x.right) + ``1``; ` `    ``y.size = size(y.left) + size(y.right) + ``1``; ` ` `  `    ``// Return new root ` `    ``return` `y; ` `} ` ` `  `// Get Balance factor of Node N ` `static` `int` `getBalance(Node N) ` `{ ` `    ``if` `(N == ``null``) ` `        ``return` `0``; ` `         `  `    ``return` `height(N.left) - height(N.right); ` `} ` ` `  `// Inserts a new key to the tree rotted ` `// with Node. Also, updates *result  ` `// (inversion count) ` `static` `Node insert(Node node, ``int` `key) ` `{ ` `     `  `    ``// 1. Perform the normal BST rotation  ` `    ``if` `(node == ``null``) ` `        ``return` `(newNode(key)); ` ` `  `    ``if` `(key < node.key) ` `    ``{ ` `        ``node.left = insert(node.left, key); ` ` `  `        ``// UPDATE COUNT OF GREATE ELEMENTS FOR KEY ` `        ``result = result + size(node.right) + ``1``; ` `    ``} ` `    ``else` `        ``node.right = insert(node.right, key); ` ` `  `    ``// 2. Update height and size of  ` `    ``// this ancestor node ` `    ``node.height = Math.max(height(node.left), ` `                           ``height(node.right)) + ``1``; ` `    ``node.size = size(node.left) +  ` `                ``size(node.right) + ``1``; ` ` `  `    ``// 3. Get the balance factor of this  ` `    ``// ancestor node to check whether this  ` `    ``// node became unbalanced  ` `    ``int` `balance = getBalance(node); ` ` `  `    ``// If this node becomes unbalanced,  ` `    ``// then there are 4 cases ` ` `  `    ``// Left Left Case ` `    ``if` `(balance > ``1` `&& key < node.left.key) ` `        ``return` `rightRotate(node); ` ` `  `    ``// Right Right Case ` `    ``if` `(balance < -``1` `&& key > node.right.key) ` `        ``return` `leftRotate(node); ` ` `  `    ``// Left Right Case ` `    ``if` `(balance > ``1` `&& key > node.left.key)  ` `    ``{ ` `        ``node.left = leftRotate(node.left); ` `        ``return` `rightRotate(node); ` `    ``} ` ` `  `    ``// Right Left Case ` `    ``if` `(balance < -``1` `&& key < node.right.key) ` `    ``{ ` `        ``node.right = rightRotate(node.right); ` `        ``return` `leftRotate(node); ` `    ``} ` ` `  `    ``// Return the (unchanged) node pointer ` `    ``return` `node; ` `} ` ` `  `// The following function returns inversion  ` `// count in arr[] ` `static` `void` `getInvCount(``int` `arr[], ``int` `n) ` `{ ` `     `  `    ``// Create empty AVL Tree ` `    ``Node root = ``null``; ` ` `  `    ``// Starting from first element,  ` `    ``// insert all elements one by  ` `    ``// one in an AVL tree. ` `    ``for``(``int` `i = ``0``; i < n; i++) ` ` `  `        ``// Note that address of result  ` `        ``// is passed as insert operation ` `        ``// updates result by adding count ` `        ``// of elements greater than arr[i]  ` `        ``// on left of arr[i] ` `        ``root = insert(root, arr[i]); ` `} ` ` `  `// Driver code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``int``[] arr = ``new` `int``[] { ``8``, ``4``, ``2``, ``1` `}; ` `    ``int` `n = arr.length; ` `    ``getInvCount(arr, n); ` `     `  `    ``System.out.print(``"Number of inversions "` `+  ` `                     ``"count are : "` `+ result); ` `} ` `} ` ` `  `// This code is contributed by tushar_bansal `

## Python3

 `# An AVL Tree based Python program to  ` `# count inversion in an array  ` ` `  `# A utility function to get height of  ` `# the tree rooted with N  ` `def` `height(N): ` `    ``if` `N ``=``=` `None``:  ` `        ``return` `0` `    ``return` `N.height ` ` `  `# A utility function to size of the ` `# tree of rooted with N  ` `def` `size(N): ` `    ``if` `N ``=``=` `None``:  ` `        ``return` `0` `    ``return` `N.size ` ` `  `# Helper function that allocates a new  ` `# Node with the given key and NULL left ` `# and right pointers.  ` `class` `newNode: ` `    ``def` `__init__(``self``, key): ` `        ``self``.key ``=` `key  ` `        ``self``.left ``=` `self``.right ``=` `None` `        ``self``.height ``=` `self``.size ``=` `1` ` `  `# A utility function to right rotate ` `# subtree rooted with y  ` `def` `rightRotate(y): ` `    ``x ``=` `y.left  ` `    ``T2 ``=` `x.right  ` ` `  `    ``# Perform rotation  ` `    ``x.right ``=` `y  ` `    ``y.left ``=` `T2  ` ` `  `    ``# Update heights  ` `    ``y.height ``=` `max``(height(y.left),  ` `                   ``height(y.right)) ``+` `1` `    ``x.height ``=` `max``(height(x.left),  ` `                   ``height(x.right)) ``+` `1` ` `  `    ``# Update sizes  ` `    ``y.size ``=` `size(y.left) ``+` `size(y.right) ``+` `1` `    ``x.size ``=` `size(x.left) ``+` `size(x.right) ``+` `1` ` `  `    ``# Return new root  ` `    ``return` `x ` ` `  `# A utility function to left rotate  ` `# subtree rooted with x  ` `def` `leftRotate(x): ` `    ``y ``=` `x.right  ` `    ``T2 ``=` `y.left  ` ` `  `    ``# Perform rotation  ` `    ``y.left ``=` `x  ` `    ``x.right ``=` `T2  ` ` `  `    ``# Update heights  ` `    ``x.height ``=` `max``(height(x.left),  ` `                   ``height(x.right)) ``+` `1` `    ``y.height ``=` `max``(height(y.left),  ` `                   ``height(y.right)) ``+` `1` ` `  `    ``# Update sizes  ` `    ``x.size ``=` `size(x.left) ``+` `size(x.right) ``+` `1` `    ``y.size ``=` `size(y.left) ``+` `size(y.right) ``+` `1` ` `  `    ``# Return new root  ` `    ``return` `y ` ` `  `# Get Balance factor of Node N  ` `def` `getBalance(N): ` `    ``if` `N ``=``=` `None``: ` `        ``return` `0` `    ``return` `height(N.left) ``-` `height(N.right) ` ` `  `# Inserts a new key to the tree rotted  ` `# with Node. Also, updates *result (inversion count)  ` `def` `insert(node, key, result): ` `     `  `    ``# 1. Perform the normal BST rotation  ` `    ``if` `node ``=``=` `None``:  ` `        ``return` `newNode(key) ` ` `  `    ``if` `key < node.key: ` `        ``node.left ``=` `insert(node.left, key, result)  ` ` `  `        ``# UPDATE COUNT OF GREATE ELEMENTS FOR KEY  ` `        ``result[``0``] ``=` `result[``0``] ``+` `size(node.right) ``+` `1` `    ``else``: ` `        ``node.right ``=` `insert(node.right, key, result)  ` ` `  `    ``# 2. Update height and size of this ancestor node  ` `    ``node.height ``=` `max``(height(node.left),     ` `                      ``height(node.right)) ``+` `1` `    ``node.size ``=` `size(node.left) ``+` `size(node.right) ``+` `1` ` `  `    ``# 3. Get the balance factor of this ancestor ` `    ``#     node to check whether this node became  ` `    ``#    unbalanced  ` `    ``balance ``=` `getBalance(node)  ` ` `  `    ``# If this node becomes unbalanced,   ` `    ``# then there are 4 cases  ` ` `  `    ``# Left Left Case  ` `    ``if` `(balance > ``1` `and` `key < node.left.key):  ` `        ``return` `rightRotate(node)  ` ` `  `    ``# Right Right Case  ` `    ``if` `(balance < ``-``1` `and` `key > node.right.key): ` `        ``return` `leftRotate(node)  ` ` `  `    ``# Left Right Case  ` `    ``if` `balance > ``1` `and` `key > node.left.key: ` `        ``node.left ``=` `leftRotate(node.left)  ` `        ``return` `rightRotate(node) ` ` `  `    ``# Right Left Case  ` `    ``if` `balance < ``-``1` `and` `key < node.right.key: ` `        ``node.right ``=` `rightRotate(node.right)  ` `        ``return` `leftRotate(node) ` ` `  `    ``# return the (unchanged) node pointer  ` `    ``return` `node ` ` `  `# The following function returns  ` `# inversion count in arr[]  ` `def` `getInvCount(arr, n): ` `    ``root ``=` `None` `# Create empty AVL Tree  ` ` `  `    ``result ``=` `[``0``] ``# Initialize result  ` ` `  `    ``# Starting from first element, insert all  ` `    ``# elements one by one in an AVL tree.  ` `    ``for` `i ``in` `range``(n):  ` ` `  `        ``# Note that address of result is passed  ` `        ``# as insert operation updates result by  ` `        ``# adding count of elements greater than  ` `        ``# arr[i] on left of arr[i]  ` `        ``root ``=` `insert(root, arr[i], result)  ` ` `  `    ``return` `result[``0``] ` ` `  `# Driver Code ` `if` `__name__ ``=``=` `'__main__'``: ` `    ``arr ``=` `[``8``, ``4``, ``2``, ``1``]  ` `    ``n ``=` `len``(arr)  ` `    ``print``(``"Number of inversions count are :"``, ` `                         ``getInvCount(arr, n)) ` ` `  `# This code is contributed by PranchalK `

Output:

```Number of inversions count are: 6
```

Complexity Analysis:

• Time Complexity: O(n Log n).
Insertion in an AVL insert takes O(log n) time and n elements are inserted in the tree so time complexity is O(n log n).
• Space Complexity: O(n).
To create a AVL tree with max n nodes O(n) extra space is required.

Counting Inversions using Set in C++ STL.
We will soon be discussing Binary Indexed Tree based approach for the same.
{"ft_lang_label":"__label__en","ft_lang_prob":0.63667923,"math_prob":0.9870616,"size":15129,"snap":"2020-45-2020-50","text_gpt3_token_len":4284,"char_repetition_ratio":0.15642975,"word_repetition_ratio":0.22804429,"special_character_ratio":0.30266374,"punctuation_ratio":0.14868902,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9998258,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-12-05T06:21:41Z\",\"WARC-Record-ID\":\"<urn:uuid:44e52886-e4aa-45ef-890f-699f2292dc04>\",\"Content-Length\":\"193199\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:cf1c5f37-fe7c-4fd3-9119-b25800df3a31>\",\"WARC-Concurrent-To\":\"<urn:uuid:3c7a270f-37e4-4c05-94ba-d2ce1a6b26ef>\",\"WARC-IP-Address\":\"104.96.220.120\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/count-inversions-in-an-array-set-2-using-self-balancing-bst/\",\"WARC-Payload-Digest\":\"sha1:MM5UJBUPOG6LABN4SCX7CSX2L7GEURFY\",\"WARC-Block-Digest\":\"sha1:MXQSSQSUYIAV7MKNKK3YFQT2DKCHT2SW\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-50/CC-MAIN-2020-50_segments_1606141746320.91_warc_CC-MAIN-20201205044004-20201205074004-00210.warc.gz\"}"}