Inversion count in Array Using SelfBalancing BST (original) (raw)

Inversion count in Array Using Self-Balancing BST

Last Updated : 16 Dec, 2024

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

**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. 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 &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: