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:

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:
- Create an AVL tree, with a property that every node will contain the size of its subtree.
- Traverse the array from start to the end.
- For every element insert the element in the AVL tree.
- 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.
- So increase the count by size of subtree of right child of the current inserted node.
- return the count.
C++
// C++ Program to count inversions using
// an AVL Tree
#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int key, height, size;
Node *left;
Node *right;
Node(int val) {
key = val;
height = 1;
size = 1;
left = right = nullptr;
}
};
// Function to get the height of the tree
// rooted with n
int getHeight(Node *n) {
if (n == nullptr) {
return 0;
}
return n->height;
}
// Function to get the size of the tree
// rooted with n
int getSize(Node *n) {
if (n == nullptr) {
return 0;
}
return n->size;
}
// Function to right rotate subtree rooted with y
Node *rightRotate(Node *y) {
Node *x = y->left;
Node *curr = x->right;
// Perform rotation
x->right = y;
y->left = curr;
// Update heights
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
// Update sizes
y->size = getSize(y->left) + getSize(y->right) + 1;
x->size = getSize(x->left) + getSize(x->right) + 1;
return x;
}
// Function to left rotate subtree rooted with x
Node *leftRotate(Node *x) {
Node *y = x->right;
Node *curr = y->left;
// Perform rotation
y->left = x;
x->right = curr;
// Update heights
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
// Update sizes
x->size = getSize(x->left) + getSize(x->right) + 1;
y->size = getSize(y->left) + getSize(y->right) + 1;
return y;
}
// Get balance factor of Node n
int getBalance(Node *n) {
if (n == nullptr) {
return 0;
}
return getHeight(n->left) - getHeight(n->right);
}
// Function to insert a new key to the tree
// and update inversion count
Node *insert(Node *root, int key, int &inversionCount) {
// Perform the normal BST insertion
if (root == nullptr) {
return new Node(key);
}
if (key < root->key) {
root->left = insert(root->left, key, inversionCount);
inversionCount += getSize(root->right) + 1;
}
else {
root->right = insert(root->right, key, inversionCount);
}
// Update height and size of the current node
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
root->size = getSize(root->left) + getSize(root->right) + 1;
// Get the balance factor to check whether
// this node became unbalanced
int balance = getBalance(root);
// Left Left Case
if (balance > 1 && key < root->left->key) {
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && key > root->right->key) {
return leftRotate(root);
}
// Left Right Case
if (balance > 1 && key > root->left->key) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
// Right Left Case
if (balance < -1 && key < root->right->key) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
// Function to count inversions in a vector using AVL Tree
int countInversions(vector<int> &arr) {
Node *root = nullptr;
int inversionCount = 0;
for (int num : arr) {
root = insert(root, num, inversionCount);
}
return inversionCount;
}
int main() {
vector<int> arr = {8, 4, 2, 1};
cout << countInversions(arr) << endl;
return 0;
}
Java
// Java Program to count inversions using
// an AVL Tree
import java.util.*;
class Node {
int key, height, size;
Node left, right;
Node(int val) {
key = val;
height = 1;
size = 1;
left = right = null;
}
}
class GfG {
// Function to get the height of the
// tree rooted with n
static int getHeight(Node n) {
if (n == null) {
return 0;
}
return n.height;
}
// Function to get the size of the tree
// rooted with n
static int getSize(Node n) {
if (n == null) {
return 0;
}
return n.size;
}
// Function to right rotate subtree rooted with y
static Node rightRotate(Node y) {
Node x = y.left;
Node curr = x.right;
// Perform rotation
x.right = y;
y.left = curr;
// Update heights
y.height = Math.max(getHeight(y.left),
getHeight(y.right)) + 1;
x.height = Math.max(getHeight(x.left),
getHeight(x.right)) + 1;
// Update sizes
y.size = getSize(y.left) + getSize(y.right) + 1;
x.size = getSize(x.left) + getSize(x.right) + 1;
return x;
}
// Function to left rotate subtree rooted with x
static Node leftRotate(Node x) {
Node y = x.right;
Node curr = y.left;
// Perform rotation
y.left = x;
x.right = curr;
// Update heights
x.height = Math.max(getHeight(x.left),
getHeight(x.right)) + 1;
y.height = Math.max(getHeight(y.left),
getHeight(y.right)) + 1;
// Update sizes
x.size = getSize(x.left) + getSize(x.right) + 1;
y.size = getSize(y.left) + getSize(y.right) + 1;
return y;
}
// Get balance factor of Node n
static int getBalance(Node n) {
if (n == null) {
return 0;
}
return getHeight(n.left) - getHeight(n.right);
}
// Function to insert a new key to the tree
// and update inversion count
static Node insert(Node root, int key,
int[] inversionCount) {
// Perform the normal BST insertion
if (root == null) {
return new Node(key);
}
if (key < root.key) {
root.left = insert(root.left,
key, inversionCount);
inversionCount[0] += getSize(root.right) + 1;
}
else {
root.right = insert(root.right, key, inversionCount);
}
// Update height and size of the current node
root.height = Math.max(getHeight(root.left),
getHeight(root.right)) + 1;
root.size = getSize(root.left)
+ getSize(root.right) + 1;
// Get the balance factor to check whether this
// node became unbalanced
int balance = getBalance(root);
// Left Left Case
if (balance > 1 && key < root.left.key) {
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && key > root.right.key) {
return leftRotate(root);
}
// Left Right Case
if (balance > 1 && key > root.left.key) {
root.left = leftRotate(root.left);
return rightRotate(root);
}
// Right Left Case
if (balance < -1 && key < root.right.key) {
root.right = rightRotate(root.right);
return leftRotate(root);
}
return root;
}
// Function to count inversions in a list using AVL Tree
static int countInversions(List<Integer> arr) {
Node root = null;
int[] inversionCount = {0};
for (int num : arr) {
root = insert(root, num, inversionCount);
}
return inversionCount[0];
}
public static void main(String[] args) {
List<Integer> arr = Arrays.asList(8, 4, 2, 1);
System.out.println(countInversions(arr));
}
}
Python
# Python Program to count inversions
# using an AVL Tree
class Node:
def __init__(self, val):
self.key = val
self.height = 1
self.size = 1
self.left = None
self.right = None
def GetHeight(n):
if n is None:
return 0
return n.height
def GetSize(n):
if n is None:
return 0
return n.size
def RightRotate(y):
x = y.left
curr = x.right
# Perform rotation
x.right = y
y.left = curr
# Update heights
y.height = max(GetHeight(y.left), GetHeight(y.right)) + 1
x.height = max(GetHeight(x.left), GetHeight(x.right)) + 1
# Update sizes
y.size = GetSize(y.left) + GetSize(y.right) + 1
x.size = GetSize(x.left) + GetSize(x.right) + 1
return x
def LeftRotate(x):
y = x.right
curr = y.left
# Perform rotation
y.left = x
x.right = curr
# Update heights
x.height = max(GetHeight(x.left), GetHeight(x.right)) + 1
y.height = max(GetHeight(y.left), GetHeight(y.right)) + 1
# Update sizes
x.size = GetSize(x.left) + GetSize(x.right) + 1
y.size = GetSize(y.left) + GetSize(y.right) + 1
return y
def GetBalance(n):
if n is None:
return 0
return GetHeight(n.left) - GetHeight(n.right)
def Insert(root, key, inversionCount):
# Perform the normal BST insertion
if root is None:
return Node(key)
if key < root.key:
root.left = Insert(root.left, key, inversionCount)
inversionCount[0] += GetSize(root.right) + 1
else:
root.right = Insert(root.right, key, inversionCount)
# Update height and size of the current node
root.height = max(GetHeight(root.left), GetHeight(root.right)) + 1
root.size = GetSize(root.left) + GetSize(root.right) + 1
# Get the balance factor to check whether this
# node became unbalanced
balance = GetBalance(root)
# Left Left Case
if balance > 1 and key < root.left.key:
return RightRotate(root)
# Right Right Case
if balance < -1 and key > root.right.key:
return LeftRotate(root)
# Left Right Case
if balance > 1 and key > root.left.key:
root.left = LeftRotate(root.left)
return RightRotate(root)
# Right Left Case
if balance < -1 and key < root.right.key:
root.right = RightRotate(root.right)
return LeftRotate(root)
return root
def CountInversions(arr):
root = None
inversionCount = [0]
for num in arr:
root = Insert(root, num, inversionCount)
return inversionCount[0]
if __name__ == "__main__":
arr = [8, 4, 2, 1]
print(CountInversions(arr))
C#
// C# Program to count inversions using
// an AVL Tree
using System;
using System.Collections.Generic;
class Node {
public int key, height, size;
public Node left, right;
public Node(int val) {
key = val;
height = 1;
size = 1;
left = right = null;
}
}
class GfG {
// Function to get the height of the
// tree rooted with n
static int GetHeight(Node n) {
if (n == null) {
return 0;
}
return n.height;
}
// Function to get the size of the tree rooted with n
static int GetSize(Node n) {
if (n == null) {
return 0;
}
return n.size;
}
// Function to right rotate subtree rooted with y
static Node RightRotate(Node y) {
Node x = y.left;
Node curr = x.right;
// Perform rotation
x.right = y;
y.left = curr;
// Update heights
y.height = Math.Max(GetHeight(y.left),
GetHeight(y.right))
+ 1;
x.height = Math.Max(GetHeight(x.left),
GetHeight(x.right))
+ 1;
// Update sizes
y.size = GetSize(y.left) + GetSize(y.right) + 1;
x.size = GetSize(x.left) + GetSize(x.right) + 1;
return x;
}
// Function to left rotate subtree rooted with x
static Node LeftRotate(Node x) {
Node y = x.right;
Node curr = y.left;
// Perform rotation
y.left = x;
x.right = curr;
// Update heights
x.height = Math.Max(GetHeight(x.left),
GetHeight(x.right))
+ 1;
y.height = Math.Max(GetHeight(y.left),
GetHeight(y.right))
+ 1;
// Update sizes
x.size = GetSize(x.left) + GetSize(x.right) + 1;
y.size = GetSize(y.left) + GetSize(y.right) + 1;
return y;
}
// Get balance factor of Node n
static int GetBalance(Node n) {
if (n == null) {
return 0;
}
return GetHeight(n.left) - GetHeight(n.right);
}
// Function to insert a new key to the tree and update
// inversion count
static Node Insert(Node root, int key,
int[] inversionCount) {
// Perform the normal BST insertion
if (root == null) {
return new Node(key);
}
if (key < root.key) {
root.left
= Insert(root.left, key, inversionCount);
inversionCount[0] += GetSize(root.right) + 1;
}
else {
root.right
= Insert(root.right, key, inversionCount);
}
// Update height and size of the current node
root.height = Math.Max(GetHeight(root.left),
GetHeight(root.right))
+ 1;
root.size
= GetSize(root.left) + GetSize(root.right) + 1;
// Get the balance factor to check whether this
// node became unbalanced
int balance = GetBalance(root);
// Left Left Case
if (balance > 1 && key < root.left.key) {
return RightRotate(root);
}
// Right Right Case
if (balance < -1 && key > root.right.key) {
return LeftRotate(root);
}
// Left Right Case
if (balance > 1 && key > root.left.key) {
root.left = LeftRotate(root.left);
return RightRotate(root);
}
// Right Left Case
if (balance < -1 && key < root.right.key) {
root.right = RightRotate(root.right);
return LeftRotate(root);
}
return root;
}
// Function to count inversions in a list using AVL Tree
static int CountInversions(List<int> arr) {
Node root = null;
int[] inversionCount = { 0 };
foreach(int num in arr) {
root = Insert(root, num, inversionCount);
}
return inversionCount[0];
}
static void Main(string[] args) {
List<int> arr = new List<int>{ 8, 4, 2, 1 };
Console.WriteLine(CountInversions(arr));
}
}
JavaScript
// JavaScript Program to count inversions using
// an AVL Tree
class Node {
constructor(key) {
this.key = key;
this.height = 1;
this.size = 1;
this.left = null;
this.right = null;
}
}
// Function to get the height of the tree
// rooted with node
function getHeight(node) {
return node === null ? 0 : node.height;
}
// Function to get the size of the tree
// rooted with node
function getSize(node) {
return node === null ? 0 : node.size;
}
// Function to right rotate subtree rooted with y
function rightRotate(y) {
let x = y.left;
let curr = x.right;
// Perform rotation
x.right = y;
y.left = curr;
// Update heights
y.height = Math.max(getHeight(y.left),
getHeight(y.right)) + 1;
x.height = Math.max(getHeight(x.left),
getHeight(x.right)) + 1;
// Update sizes
y.size = getSize(y.left) + getSize(y.right) + 1;
x.size = getSize(x.left) + getSize(x.right) + 1;
return x;
}
// Function to left rotate subtree rooted with x
function leftRotate(x) {
let y = x.right;
let curr = y.left;
// Perform rotation
y.left = x;
x.right = curr;
// Update heights
x.height = Math.max(getHeight(x.left),
getHeight(x.right)) + 1;
y.height = Math.max(getHeight(y.left),
getHeight(y.right)) + 1;
// Update sizes
x.size = getSize(x.left) + getSize(x.right) + 1;
y.size = getSize(y.left) + getSize(y.right) + 1;
return y;
}
// Get balance factor of node
function getBalance(node) {
return node === null ? 0 : getHeight(node.left)
- getHeight(node.right);
}
// Function to insert a new key to the tree
// and update inversion count
function insert(root, key, inversionCount) {
// Perform the normal BST insertion
if (root === null) {
return new Node(key);
}
if (key < root.key) {
root.left = insert(root.left, key, inversionCount);
inversionCount.count += getSize(root.right) + 1;
}
else {
root.right = insert(root.right, key, inversionCount);
}
// Update height and size of the current node
root.height = Math.max(getHeight(root.left),
getHeight(root.right)) + 1;
root.size = getSize(root.left) + getSize(root.right) + 1;
// Get the balance factor to check whether
// this node became unbalanced
let balance = getBalance(root);
// Left Left Case
if (balance > 1 && key < root.left.key) {
return rightRotate(root);
}
// Right Right Case
if (balance < -1 && key > root.right.key) {
return leftRotate(root);
}
// Left Right Case
if (balance > 1 && key > root.left.key) {
root.left = leftRotate(root.left);
return rightRotate(root);
}
// Right Left Case
if (balance < -1 && key < root.right.key) {
root.right = rightRotate(root.right);
return leftRotate(root);
}
return root;
}
// Function to count inversions in an array
// using AVL Tree
function countInversions(arr) {
let root = null;
let inversionCount = { count: 0 };
for (let num of arr) {
root = insert(root, num, inversionCount);
}
return inversionCount.count;
}
const arr = [8, 4, 2, 1];
console.log(countInversions(arr));
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:
Similar Reads
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem