Given an array, count the total number of triplets, which leads to an inversion. If (i < j < k) and (A[i] > A[j] > A[k]), then we can say that triplet (i, j, k) formed an inversion in an array A.

For example,

Input:  A[] = [1, 9, 6, 4, 5]
Output: The inversion count is 2
 
There are two inversions of size three in the array:
(9, 6, 4) and (9, 6, 5).
 
 
Input:  A[] = [9, 4, 3, 5, 1]
Output: The inversion count is 5
 
There are five inversions of size three in the array:
(9, 4, 3), (9, 4, 1), (9, 3, 1), (4, 3, 1), and (9, 5, 1).

Practice this problem

A naive solution is to consider each triplet (A[i], A[j], A[k]) in array A by looping through all possible value of i, j and k. If the inversion condition is satisfied by a triplet, then increment the inversion count. The time complexity of this solution is O(n3), where n is the size of the input.

The implementation can be seen below in C, Java, and Python:

C


Download  Run Code

Output:

The inversion count is 5

Java


Download  Run Code

Output:

The inversion count is 5

Python


Download  Run Code

Output:

The inversion count is 5

We can easily reduce the time complexity of the solution from O(n3) to O(n2). The idea is to consider each element in array arr[j] as the middle element of the triplet. Then the total number of inversions with arr[j] as the middle element is the product of the total number of elements greater than arr[j] with index less than j with the total number of elements smaller than arr[j] with index more than j.

Basically, for each array element, we count all elements more than it to its left and all elements less than it to its right and add their product to the result. Following is the C, Java, and Python program that demonstrates it:

C


Download  Run Code

Output:

The inversion count is 5

Java


Download  Run Code

Output:

The inversion count is 5

Python


Download  Run Code

Output:

The inversion count is 5