Count Inversions of size three in a given array
Last Updated :
20 Mar, 2023
Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3.
Example :
Input: {8, 4, 2, 1}
Output: 4
The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).
Input: {9, 6, 4, 5, 8}
Output: 2
The two inversions are {9, 6, 4} and {9, 6, 5}
We have already discussed inversion count of size two by merge sort, Self Balancing BST and BIT.
Simple approach: Loop for all possible value of i, j and k and check for the condition a[i] > a[j] > a[k] and i < j < k.
C++
#include<bits/stdc++.h>
using namespace std;
int getInvCount( int arr[], int n)
{
int invcount = 0;
for ( int i=0; i<n-2; i++)
{
for ( int j=i+1; j<n-1; j++)
{
if (arr[i]>arr[j])
{
for ( int k=j+1; k<n; k++)
{
if (arr[j]>arr[k])
invcount++;
}
}
}
}
return invcount;
}
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "Inversion Count : " << getInvCount(arr, n);
return 0;
}
|
Java
class Inversion{
int getInvCount( int arr[], int n)
{
int invcount = 0 ;
for ( int i= 0 ; i< n- 2 ; i++)
{
for ( int j=i+ 1 ; j<n- 1 ; j++)
{
if (arr[i] > arr[j])
{
for ( int k=j+ 1 ; k<n; k++)
{
if (arr[j] > arr[k])
invcount++;
}
}
}
}
return invcount;
}
public static void main(String args[])
{
Inversion inversion = new Inversion();
int arr[] = new int [] { 8 , 4 , 2 , 1 };
int n = arr.length;
System.out.print( "Inversion count : " +
inversion.getInvCount(arr, n));
}
}
|
Python3
def getInvCount(arr):
n = len (arr)
invcount = 0
for i in range ( 0 ,n - 1 ):
for j in range (i + 1 , n):
if arr[i] > arr[j]:
for k in range (j + 1 , n):
if arr[j] > arr[k]:
invcount + = 1
return invcount
arr = [ 8 , 4 , 2 , 1 ]
print ( "Inversion Count : %d" % (getInvCount(arr)))
|
C#
using System;
class GFG {
static int getInvCount( int []arr, int n)
{
int invcount = 0;
for ( int i = 0 ; i < n - 2; i++)
{
for ( int j = i + 1; j < n - 1; j++)
{
if (arr[i] > arr[j])
{
for ( int k = j + 1; k < n; k++)
{
if (arr[j] > arr[k])
invcount++;
}
}
}
}
return invcount;
}
public static void Main()
{
int []arr = new int [] {8, 4, 2, 1};
int n = arr.Length;
Console.WriteLine( "Inversion count : " +
getInvCount(arr, n));
}
}
|
PHP
<?php
function getInvCount( $arr , $n )
{
$invcount = 0;
for ( $i = 1; $i < $n - 1; $i ++)
{
$small = 0;
for ( $j = $i + 1; $j < $n ; $j ++)
if ( $arr [ $i ] > $arr [ $j ])
$small ++;
$great = 0;
for ( $j = $i - 1; $j >= 0; $j --)
if ( $arr [ $i ] < $arr [ $j ])
$great ++;
$invcount += $great * $small ;
}
return $invcount ;
}
$arr = array (8, 4, 2, 1);
$n = sizeof( $arr );
echo "Inversion Count : "
, getInvCount( $arr , $n );
?>
|
Javascript
<script>
function getInvCount(arr, n)
{
let invcount = 0;
for (let i = 0 ; i < n - 2; i++)
{
for (let j = i + 1; j < n - 1; j++)
{
if (arr[i] > arr[j])
{
for (let k = j + 1; k < n; k++)
{
if (arr[j] > arr[k])
invcount++;
}
}
}
}
return invcount;
}
let arr = [8, 4, 2, 1];
let n = arr.length;
document.write( "Inversion count : " +
getInvCount(arr, n));
</script>
|
Output
Inversion Count : 4
Time complexity: O(n^3)
Auxiliary Space: O(1).
Better Approach :
We can reduce the complexity if we consider every element arr[i] as middle element of inversion, find all the numbers greater than a[i] whose index is less than i, find all the numbers which are smaller than a[i] and index is more than i. We multiply the number of elements greater than a[i] to the number of elements smaller than a[i] and add it to the result.
Below is the implementation of the idea.
C++
#include<bits/stdc++.h>
using namespace std;
int getInvCount( int arr[], int n)
{
int invcount = 0;
for ( int i=1; i<n-1; i++)
{
int small = 0;
for ( int j=i+1; j<n; j++)
if (arr[i] > arr[j])
small++;
int great = 0;
for ( int j=i-1; j>=0; j--)
if (arr[i] < arr[j])
great++;
invcount += great*small;
}
return invcount;
}
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "Inversion Count : " << getInvCount(arr, n);
return 0;
}
|
Java
class Inversion {
int getInvCount( int arr[], int n)
{
int invcount = 0 ;
for ( int i= 0 ; i< n- 1 ; i++)
{
int small= 0 ;
for ( int j=i+ 1 ; j<n; j++)
if (arr[i] > arr[j])
small++;
int great = 0 ;
for ( int j=i- 1 ; j>= 0 ; j--)
if (arr[i] < arr[j])
great++;
invcount += great*small;
}
return invcount;
}
public static void main(String args[])
{
Inversion inversion = new Inversion();
int arr[] = new int [] { 8 , 4 , 2 , 1 };
int n = arr.length;
System.out.print( "Inversion count : " +
inversion.getInvCount(arr, n));
}
}
|
Python3
def getInvCount(arr, n):
invcount = 0
for i in range ( 1 ,n - 1 ):
small = 0
for j in range (i + 1 ,n):
if (arr[i] > arr[j]):
small + = 1
great = 0 ;
for j in range (i - 1 , - 1 , - 1 ):
if (arr[i] < arr[j]):
great + = 1
invcount + = great * small
return invcount
arr = [ 8 , 4 , 2 , 1 ]
n = len (arr)
print ( "Inversion Count :" ,getInvCount(arr, n))
|
C#
using System;
public class Inversion {
static int getInvCount( int []arr, int n)
{
int invcount = 0;
for ( int i = 0 ; i < n-1; i++)
{
int small = 0;
for ( int j = i+1; j < n; j++)
if (arr[i] > arr[j])
small++;
int great = 0;
for ( int j = i-1; j >= 0; j--)
if (arr[i] < arr[j])
great++;
invcount += great * small;
}
return invcount;
}
public static void Main()
{
int []arr = new int [] {8, 4, 2, 1};
int n = arr.Length;
Console.WriteLine( "Inversion count : "
+ getInvCount(arr, n));
}
}
|
PHP
<?php
function getInvCount( $arr , $n )
{
$invcount = 0;
for ( $i = 1; $i < $n - 1; $i ++)
{
$small = 0;
for ( $j = $i + 1; $j < $n ; $j ++)
if ( $arr [ $i ] > $arr [ $j ])
$small ++;
$great = 0;
for ( $j = $i - 1; $j >= 0; $j --)
if ( $arr [ $i ] < $arr [ $j ])
$great ++;
$invcount += $great * $small ;
}
return $invcount ;
}
$arr = array (8, 4, 2, 1);
$n = sizeof( $arr );
echo "Inversion Count : " ,
getInvCount( $arr , $n );
?>
|
Javascript
<script>
function getInvCount(arr, n)
{
let invcount = 0;
for (let i = 0 ; i < n - 1; i++)
{
let small = 0;
for (let j = i + 1; j < n; j++)
if (arr[i] > arr[j])
small++;
let great = 0;
for (let j = i - 1; j >= 0; j--)
if (arr[i] < arr[j])
great++;
invcount += great*small;
}
return invcount;
}
let arr=[8, 4, 2, 1];
let n = arr.length;
document.write( "Inversion count : " +getInvCount(arr, n));
</script>
|
Output
Inversion Count : 4
Time Complexity: O(n^2)
Auxiliary Space: O(1).
Binary Indexed Tree Approach :
Like inversions of size 2, we can use Binary indexed tree to find inversions of size 3. It is strongly recommended to refer below article first.
Count inversions of size two Using BIT
The idea is similar to above method. We count the number of greater elements and smaller elements for all the elements and then multiply greater[] to smaller[] and add it to the result.
Solution :
- To find out the number of smaller elements for an index we iterate from n-1 to 0. For every element a[i] we calculate the getSum() function for (a[i]-1) which gives the number of elements till a[i]-1.
- To find out the number of greater elements for an index we iterate from 0 to n-1. For every element a[i] we calculate the sum of numbers till a[i] (sum smaller or equal to a[i]) by getSum() and subtract it from i (as i is the total number of element till that point) so that we can get number of elements greater than a[i].
Below is the code for the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int BIT[3][N] = { 0 };
void updateBIT( int t, int i, int val, int n)
{
while (i <= n) {
BIT[t][i] = BIT[t][i] + val;
i = i + (i & (-i));
}
}
int getSum( int t, int i)
{
int res = 0;
while (i > 0) {
res = res + BIT[t][i];
i = i - (i & (-i));
}
return res;
}
void convert( int arr[], int n)
{
int temp[n];
for ( int i = 0; i < n; i++)
temp[i] = arr[i];
sort(temp, temp + n);
for ( int i = 0; i < n; i++) {
arr[i] = lower_bound(temp, temp + n,
arr[i]) - temp + 1;
}
}
int getInvCount( int arr[], int n)
{
convert(arr, n);
for ( int i = n - 1; i >= 0; i--) {
updateBIT(1, arr[i], 1, n);
for ( int l = 1; l < 3; l++) {
updateBIT(l + 1, arr[i], getSum(l, arr[i] - 1), n);
}
}
return getSum(3, n);
}
int main()
{
int arr[] = {8, 4, 2, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "Inversion Count : " << getInvCount(arr, n);
return 0;
}
|
Java
import java.io.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.lang.*;
import java.util.Collections;
class GFG {
static int N = 100005 ;
static int BIT[][] = new int [ 4 ][N];
static void updateBIT( int t, int i, int val, int n)
{
while (i <= n) {
BIT[t][i] = BIT[t][i] + val;
i = i + (i & (-i));
}
}
static int getSum( int t, int i)
{
int res = 0 ;
while (i > 0 ) {
res = res + BIT[t][i];
i = i - (i & (-i));
}
return res;
}
static void convert( int arr[], int n)
{
int temp[]= new int [n];
for ( int i = 0 ; i < n; i++)
temp[i] = arr[i];
Arrays.sort(temp);
for ( int i = 0 ; i < n; i++) {
arr[i] = Arrays.binarySearch(temp,arr[i]) + 1 ;
}
}
static int getInvCount( int arr[], int n)
{
convert(arr, n);
for ( int i = n - 1 ; i >= 0 ; i--) {
updateBIT( 1 , arr[i], 1 , n);
for ( int l = 1 ; l < 3 ; l++) {
updateBIT(l + 1 , arr[i], getSum(l, arr[i] - 1 ), n);
}
}
return getSum( 3 , n);
}
public static void main (String[] args)
{
int arr[] = { 8 , 4 , 2 , 1 };
int n = arr.length;
System.out.print( "Inversion Count : " +getInvCount(arr, n));
}
}
|
Python3
N = 100005
BIT = [[ 0 for x in range (N)] for y in range ( 3 )]
for i in range ( 0 , 50 ):
abc = [ 0 ] * 50
BIT.append(abc)
def updateBIT(t, i, val, n):
while i < = n:
BIT[t][i] = BIT[t][i] + val
i = i + (i & ( - i))
def getSum(t, i):
res = 0
while i > 0 :
res = res + BIT[t][i]
i = i - (i & ( - i))
return res
def convert(arr, n):
temp = [ 0 for x in range (n)]
for i in range (n):
temp[i] = arr[i]
temp.sort()
for i in range (n):
arr[i] = temp.index(arr[i]) + 1
def getInvCount(arr, n):
convert(arr, n)
for i in range (n - 1 , - 1 , - 1 ):
updateBIT( 1 , arr[i], 1 , n)
for l in range ( 1 , 3 ):
updateBIT(l + 1 , arr[i], getSum(l, arr[i] - 1 ), n)
return getSum( 3 , n)
arr = [ 8 , 4 , 2 , 1 ]
n = len (arr)
print ( "Inversion Count : " , getInvCount(arr, n))
|
Javascript
const N = 100005;
let BIT = [[0], [0], [0]];
for (let i = 0; i < 10; i++) {
let abc = [0];
BIT.push(abc);
}
function updateBIT(t, i, val, n) {
while (i <= n) {
if (!BIT[t][i]) BIT[t][i] = 0;
BIT[t][i] = BIT[t][i] + val;
i = i + (i & (-i));
}
}
function getSum(t, i) {
let res = 0;
while (i > 0) {
res = res + BIT[t][i];
i = i - (i & (-i));
}
return res;
}
function convert(arr, n) {
let temp = [];
for (let i = 0; i < n; i++)
temp[i] = arr[i];
temp.sort();
for (let i = 0; i < n; i++) {
arr[i] = temp.indexOf(arr[i]) + 1;
}
}
function getInvCount(arr, n) {
convert(arr, n);
for (let i = n - 1; i >= 0; i--) {
updateBIT(1, arr[i], 1, n);
for (let l = 1; l < 3; l++) {
updateBIT(l + 1, arr[i], getSum(l, arr[i] - 1), n);
}
}
return getSum(3, n);
}
let arr = [8, 4, 2, 1];
let n = arr.length;
console.log( "Inversion Count : " + getInvCount(arr, n));
|
C#
using System;
class GFG
{
static int N = 100005;
static int [,] BIT = new int [4, N];
static void updateBIT( int t, int i, int val, int n)
{
while (i <= n)
{
BIT[t, i] = BIT[t, i] + val;
i = i + (i & (-i));
}
}
static int getSum( int t, int i)
{
int res = 0;
while (i > 0)
{
res = res + BIT[t, i];
i = i - (i & (-i));
}
return res;
}
static void convert( int [] arr, int n)
{
int [] temp = new int [n];
for ( int i = 0; i < n; i++)
temp[i] = arr[i];
Array.Sort(temp);
for ( int i = 0; i < n; i++)
{
arr[i] = Array.BinarySearch(temp, arr[i]) + 1;
}
}
static int getInvCount( int [] arr, int n)
{
convert(arr, n);
for ( int i = n - 1; i >= 0; i--)
{
updateBIT(1, arr[i], 1, n);
for ( int l = 1; l < 3; l++)
{
updateBIT(l + 1, arr[i], getSum(l, arr[i] - 1), n);
}
}
return getSum(3, n);
}
static void Main( string [] args)
{
int [] arr = { 8, 4, 2, 1 };
int n = arr.Length;
Console.Write( "Inversion Count : " + getInvCount(arr, n));
}
}
|
Output
Inversion Count : 4
Time Complexity: O(n*log(n))
Auxiliary Space: O(n).
Similar Reads
Javascript Program to Count Inversions of size three in a given array
Given an array arr[] of size n. Three elements arr[i], arr[j] and arr[k] form an inversion of size 3 if a[i] > a[j] >a[k] and i < j < k. Find total number of inversions of size 3. Example : Input: {8, 4, 2, 1}Output: 4The four inversions are (8,4,2), (8,4,1), (4,2,1) and (8,2,1).Input: {
4 min read
Count of Integers in given Array whose MSB and LSB are set
Given an array A[] of length N, the task is to count the number of elements of the array having their MSB and LSB set. Examples: Input: A[] = {2, 3, 1, 5}Output: 3Explanation: Binary representation of the array elements {2, 3, 1, 5} are {10, 11, 1, 101}The integers 3, 1, 5 are the integers whose fir
9 min read
Count 1s present in a range of indices [L, R] in a given array
Given an array arr[] consisting of a single element N (1 ⤠N ⤠106) and two integers L and R, ( 1 ⤠L ⤠R ⤠105), the task is to make all array elements either 0 or 1 using the following operations : Select an element P such that P > 1 from the array arr[].Replace P with three elements at the sam
10 min read
Count of triplets in a given Array having GCD K
Given an integer array arr[] and an integer K, the task is to count all triplets whose GCD is equal to K.Examples: Input: arr[] = {1, 4, 8, 14, 20}, K = 2 Output: 3 Explanation: Triplets (4, 14, 20), (8, 14, 20) and (4, 8, 14) have GCD equal to 2.Input: arr[] = {1, 2, 3, 4, 5}, K = 7 Output: 0 Appro
8 min read
3 Sum - Count Triplets With Given Sum In Sorted Array
Given a sorted array arr[] and a target value, the task is to find the count of triplets present in the given array having sum equal to the given target. More specifically, the task is to count triplets (i, j, k) of valid indices, such that arr[i] + arr[j] + arr[k] = target and i < j < k. Exam
10 min read
Count subsequence of length three in a given string
Given a string of length n and a subsequence of length 3. Find the total number of occurrences of the subsequence in this string. Examples : Input : string = "GFGFGYSYIOIWIN", subsequence = "GFG" Output : 4 Explanation : There are 4 such subsequences as shown: GFGFGYSYIOIWIN GFGFGYSYIOIWIN GFGFGYSYI
15 min read
Count subarrays with non-zero sum in the given Array
Given an array arr[] of size N, the task is to count the total number of subarrays for the given array arr[] which have a non-zero-sum.Examples: Input: arr[] = {-2, 2, -3} Output: 4 Explanation: The subarrays with non zero sum are: [-2], [2], [2, -3], [-3]. All possible subarray of the given input a
7 min read
Count quadruples of given type from given array
Given an array arr[], the task is to find the number of quadruples of the form a[i] = a[k] and a[j] = a[l] ( 0 <= i < j < k < l <= N ) from the given array. Examples: Input: arr[] = {1, 2, 4, 2, 1, 5, 2}Output: 2Explanation: The quadruple {1, 2, 1, 2} occurs twice in the array, at ind
13 min read
Count of triplets in an Array with odd sum
Given an array arr[] with N integers, find the number of triplets of i, j and k such that 1<= i < j < k <= N and arr[i] + arr[j] + arr[k] is odd. Example: Input: arr[] = {1, 2, 3, 4, 5}Output: 4Explanation: The given array contains 4 triplets with an odd sum. They are {1, 2, 4}, {1, 3, 5
6 min read
Count number of occurrences (or frequency) in a sorted array
Given a sorted array arr[] and an integer target, the task is to find the number of occurrences of target in given array. Examples: Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 2Output: 4Explanation: 2 occurs 4 times in the given array. Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 4Output: 0Expl
9 min read