Count Inversions of an Array
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: Inversion Count for an array indicates that 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
[Naive Approach] Using Two Nested Loops - O(n^2) Time and O(1) Space
The main idea of this approach is to count the number of inversions in an array by using nested loops, checking every possible pair of elements and counting how many such pairs satisfy the inversion condition. The outer loop starts from the first element and goes up to the second-to-last element, and for each i, the inner loop runs from the next element (i + 1) to the end of the array. This ensures that all pairs (i, j) where i < j are checked. Inside the inner loop, it checks if arr[i] > arr[j], if so, it means there is an inversion, and the invCount is incremented.
C++
#include <iostream>
#include <vector>
using namespace std;
int inversionCount(vector<int> &arr) {
int n = arr.size();
int invCount = 0;
// Loop through the array
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// If the current element is greater
// than the next, increment the count
if (arr[i] > arr[j])
invCount++;
}
}
return invCount;
}
int main() {
vector<int> arr = {4, 3, 2, 1};
cout << inversionCount(arr) << endl;
return 0;
}
C
#include <stdio.h>
int inversionCount(int arr[], int n) {
int invCount = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// If the current element is greater than the next,
// increment the count
if (arr[i] > arr[j])
invCount++;
}
}
return invCount;
}
int main() {
int arr[] = {4, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", inversionCount(arr, n));
return 0;
}
Java
import java.util.*;
class GfG {
static int inversionCount(int arr[]) {
int n = arr.length;
int invCount = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// If the current element is greater than the next,
// increment the count
if (arr[i] > arr[j])
invCount++;
}
}
return invCount;
}
public static void main(String[] args) {
int arr[] = {4, 3, 2, 1};
System.out.println(inversionCount(arr));
}
}
Python
def inversionCount(arr):
n = len(arr)
invCount = 0
for i in range(n - 1):
for j in range(i + 1, n):
# If the current element is greater than the next,
# increment the count
if arr[i] > arr[j]:
invCount += 1
return invCount
if __name__ == "__main__":
arr = [4, 3, 2, 1]
print(inversionCount(arr))
C#
using System;
class GfG {
static int inversionCount(int[] arr) {
int n = arr.Length;
int invCount = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
// If the current element is greater than the next,
// increment the count
if (arr[i] > arr[j])
invCount++;
}
}
return invCount;
}
static void Main() {
int[] arr = { 4, 3, 2, 1 };
Console.WriteLine(inversionCount(arr));
}
}
JavaScript
function inversionCount(arr) {
let n = arr.length;
let invCount = 0;
// Loop through the array
for (let i = 0; i < n - 1; i++) {
for (let j = i + 1; j < n; j++) {
// If the current element is greater than the next,
// increment the count
if (arr[i] > arr[j]) {
invCount++;
}
}
}
return invCount;
}
// Driver Code
let arr = [4, 3, 2, 1];
console.log(inversionCount(arr));
[Expected Approach] Using Merge Step of Merge Sort - O(n*log n) Time and O(n) Space
We can use merge sort to count the inversions in an array. First, we divide the array into two halves: left half and right half. Next, we recursively count the inversions in both halves. While merging the two halves back together, we also count how many elements from the left half array are greater than elements from the right half array, as these represent cross inversions (i.e., element from the left half of the array is greater than an element from the right half during the merging process in the merge sort algorithm). Finally, we sum the inversions from the left half, right half, and the cross inversions to get the total number of inversions in the array. This approach efficiently counts inversions while sorting the array.
Let's understand the above intuition in more detailed form, as we get to know that we have to perform the merge sort on the given array. Below images represents dividing and merging steps of merge sort.
During each merging step of the merge sort algorithm, we count cross inversions by comparing elements from the left half of the array with those from the right half. If we find an element arr[i] in the left half that is greater than an element arr[j] in the right half, we can conclude that all elements after i in the left half will also be greater than arr[j]. This allows us to count multiple inversions at once. Let's suppose if there are k elements remaining in the left half after i, then there are k cross inversions for that particular arr[j]. The rest of the merging process continues as usual, where we combine the two halves into a sorted array. This efficient counting method significantly reduces the number of comparisons needed, enhancing the overall performance of the inversion counting algorithm.
Below Illustration represents the cross inversion of a particular step during the merging process in the merge sort algorithm:
C++
#include <iostream>
#include <vector>
using namespace std;
// This function merges two sorted subarrays arr[l..m] and arr[m+1..r]
// and also counts inversions in the whole subarray arr[l..r]
int countAndMerge(vector<int>& arr, int l, int m, int r) {
// Counts in two subarrays
int n1 = m - l + 1, n2 = r - m;
// Set up two vectors for left and right halves
vector<int> left(n1), right(n2);
for (int i = 0; i < n1; i++)
left[i] = arr[i + l];
for (int j = 0; j < n2; j++)
right[j] = arr[m + 1 + j];
// Initialize inversion count (or result) and merge two halves
int res = 0;
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
// No increment in inversion count if left[] has a
// smaller or equal element
if (left[i] <= right[j])
arr[k++] = left[i++];
// If right is smaller, then it is smaller than n1-i
// elements because left[] is sorted
else {
arr[k++] = right[j++];
res += (n1 - i);
}
}
// Merge remaining elements
while (i < n1)
arr[k++] = left[i++];
while (j < n2)
arr[k++] = right[j++];
return res;
}
// Function to count inversions in the array
int countInv(vector<int>& arr, int l, int r){
int res = 0;
if (l < r) {
int m = (r + l) / 2;
// Recursively count inversions in the left and
// right halves
res += countInv(arr, l, m);
res += countInv(arr, m + 1, r);
// Count inversions such that greater element is in
// the left half and smaller in the right half
res += countAndMerge(arr, l, m, r);
}
return res;
}
int inversionCount(vector<int> &arr) {
int n = arr.size();
return countInv(arr, 0, n-1);
}
int main(){
vector<int> arr = {4, 3, 2, 1};
cout << inversionCount(arr);
return 0;
}
C
#include <stdio.h>
// This function merges two sorted subarrays arr[l..m] and arr[m+1..r]
// and also counts inversions in the whole subarray arr[l..r]
int countAndMerge(int arr[], int l, int m, int r) {
// Counts in two subarrays
int n1 = m - l + 1, n2 = r - m;
// Set up two arrays for left and right halves
int left[n1], right[n2];
for (int i = 0; i < n1; i++)
left[i] = arr[i + l];
for (int j = 0; j < n2; j++)
right[j] = arr[m + 1 + j];
// Initialize inversion count (or result)
// and merge two halves
int res = 0;
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
// No increment in inversion count
// if left[] has a smaller or equal element
if (left[i] <= right[j])
arr[k++] = left[i++];
// If right is smaller, then it is smaller than n1-i
// elements because left[] is sorted
else {
arr[k++] = right[j++];
res += (n1 - i);
}
}
// Merge remaining elements
while (i < n1)
arr[k++] = left[i++];
while (j < n2)
arr[k++] = right[j++];
return res;
}
// Function to count inversions in the array
int countInv(int arr[], int l, int r) {
int res = 0;
if (l < r) {
int m = (r + l) / 2;
// Recursively count inversions
// in the left and right halves
res += countInv(arr, l, m);
res += countInv(arr, m + 1, r);
// Count inversions such that greater element is in
// the left half and smaller in the right half
res += countAndMerge(arr, l, m, r);
}
return res;
}
int inversionCount(int arr[], int n) {
return countInv(arr, 0, n - 1);
}
int main() {
int arr[] = {4, 3, 2, 1};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", inversionCount(arr, n));
return 0;
}
Java
import java.util.*;
class GfG {
// This function merges two sorted subarrays arr[l..m] and arr[m+1..r]
// and also counts inversions in the whole subarray arr[l..r]
static int countAndMerge(int[] arr, int l, int m, int r) {
// Counts in two subarrays
int n1 = m - l + 1, n2 = r - m;
// Set up two arrays for left and right halves
int[] left = new int[n1];
int[] right = new int[n2];
for (int i = 0; i < n1; i++)
left[i] = arr[i + l];
for (int j = 0; j < n2; j++)
right[j] = arr[m + 1 + j];
// Initialize inversion count (or result)
// and merge two halves
int res = 0;
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
// No increment in inversion count
// if left[] has a smaller or equal element
if (left[i] <= right[j])
arr[k++] = left[i++];
// If right is smaller, then it is smaller than n1-i
// elements because left[] is sorted
else {
arr[k++] = right[j++];
res += (n1 - i);
}
}
// Merge remaining elements
while (i < n1)
arr[k++] = left[i++];
while (j < n2)
arr[k++] = right[j++];
return res;
}
// Function to count inversions in the array
static int countInv(int[] arr, int l, int r) {
int res = 0;
if (l < r) {
int m = (r + l) / 2;
// Recursively count inversions
// in the left and right halves
res += countInv(arr, l, m);
res += countInv(arr, m + 1, r);
// Count inversions such that greater element is in
// the left half and smaller in the right half
res += countAndMerge(arr, l, m, r);
}
return res;
}
static int inversionCount(int[] arr) {
return countInv(arr, 0, arr.length - 1);
}
public static void main(String[] args) {
int[] arr = {4, 3, 2, 1};
System.out.println(inversionCount(arr));
}
}
Python
# This function merges two sorted subarrays arr[l..m] and arr[m+1..r]
# and also counts inversions in the whole subarray arr[l..r]
def countAndMerge(arr, l, m, r):
# Counts in two subarrays
n1 = m - l + 1
n2 = r - m
# Set up two lists for left and right halves
left = arr[l:m + 1]
right = arr[m + 1:r + 1]
# Initialize inversion count (or result)
# and merge two halves
res = 0
i = 0
j = 0
k = l
while i < n1 and j < n2:
# No increment in inversion count
# if left[] has a smaller or equal element
if left[i] <= right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
res += (n1 - i)
k += 1
# Merge remaining elements
while i < n1:
arr[k] = left[i]
i += 1
k += 1
while j < n2:
arr[k] = right[j]
j += 1
k += 1
return res
# Function to count inversions in the array
def countInv(arr, l, r):
res = 0
if l < r:
m = (r + l) // 2
# Recursively count inversions
# in the left and right halves
res += countInv(arr, l, m)
res += countInv(arr, m + 1, r)
# Count inversions such that greater element is in
# the left half and smaller in the right half
res += countAndMerge(arr, l, m, r)
return res
def inversionCount(arr):
return countInv(arr, 0, len(arr) - 1)
if __name__ == "__main__":
arr = [4, 3, 2, 1]
print(inversionCount(arr))
C#
using System;
using System.Collections.Generic;
class GfG {
// This function merges two sorted subarrays arr[l..m] and arr[m+1..r]
// and also counts inversions in the whole subarray arr[l..r]
static int countAndMerge(int[] arr, int l, int m, int r) {
// Counts in two subarrays
int n1 = m - l + 1, n2 = r - m;
// Set up two arrays for left and right halves
int[] left = new int[n1];
int[] right = new int[n2];
for (int x = 0; x < n1; x++)
left[x] = arr[x + l];
for (int x = 0; x < n2; x++)
right[x] = arr[m + 1 + x];
// Initialize inversion count (or result)
// and merge two halves
int res = 0;
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
// No increment in inversion count
// if left[] has a smaller or equal element
if (left[i] <= right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
res += (n1 - i);
}
}
// Merge remaining elements
while (i < n1)
arr[k++] = left[i++];
while (j < n2)
arr[k++] = right[j++];
return res;
}
// Function to count inversions in the array
static int countInv(int[] arr, int l, int r) {
int res = 0;
if (l < r) {
int m = (r + l) / 2;
// Recursively count inversions
// in the left and right halves
res += countInv(arr, l, m);
res += countInv(arr, m + 1, r);
// Count inversions such that greater element is in
// the left half and smaller in the right half
res += countAndMerge(arr, l, m, r);
}
return res;
}
static int inversionCount(int[] arr) {
return countInv(arr, 0, arr.Length - 1);
}
static void Main() {
int[] arr = {4, 3, 2, 1};
Console.WriteLine(inversionCount(arr));
}
}
JavaScript
// This function merges two sorted subarrays arr[l..m] and arr[m+1..r]
// and also counts inversions in the whole subarray arr[l..r]
function countAndMerge(arr, l, m, r) {
// Counts in two subarrays
let n1 = m - l + 1, n2 = r - m;
// Set up two arrays for left and right halves
let left = arr.slice(l, m + 1);
let right = arr.slice(m + 1, r + 1);
// Initialize inversion count (or result)
// and merge two halves
let res = 0;
let i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
// No increment in inversion count
// if left[] has a smaller or equal element
if (left[i] <= right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
res += (n1 - i);
}
}
// Merge remaining elements
while (i < n1)
arr[k++] = left[i++];
while (j < n2)
arr[k++] = right[j++];
return res;
}
// Function to count inversions in the array
function countInv(arr, l, r) {
let res = 0;
if (l < r) {
let m = Math.floor((r + l) / 2);
// Recursively count inversions
// in the left and right halves
res += countInv(arr, l, m);
res += countInv(arr, m + 1, r);
// Count inversions such that greater element is in
// the left half and smaller in the right half
res += countAndMerge(arr, l, m, r);
}
return res;
}
function inversionCount(arr) {
return countInv(arr, 0, arr.length - 1);
}
// Driver Code
let arr = [4, 3, 2, 1];
console.log(inversionCount(arr));
Note: The above code modifies (or sorts) the input array. If we want to count only inversions, we need to create a copy of the original array and perform operation on the copy array.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 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