Count Inversions of size three in a given array - GeeksforGeeks

20 Jan, 2022
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++
Java
Python3
C#
PHP
Javascript
// A Simple C++ O(n^3)  program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns counts of inversions of size threeint getInvCount(int arr[],int n){    int invcount = 0;  // Initialize result     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;} // Driver program to test above functionint main(){    int arr[] = {8, 4, 2, 1};    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Inversion Count : " << getInvCount(arr, n);    return 0;}
// A simple Java implementation  to count inversion of size 3class Inversion{         // returns count of inversion of size 3    int getInvCount(int arr[], int n)    {        int invcount = 0; // initialize result                 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;    }     // driver program to test above function    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));    }}// This code is contributed by Mayank Jaiswal
# A simple python O(n^3) program# to count inversions of size 3 # Returns counts of inversions# of size threeedef getInvCount(arr):    n = len(arr)    invcount = 0  #Initialize result       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 # Driver program to test above functionarr = [8 , 4, 2 , 1]print ("Inversion Count : %d" %(getInvCount(arr))) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// A simple C# implementation to// count inversion of size 3using System;class GFG {     // returns count of inversion of size 3static int getInvCount(int []arr, int n)    {                 // initialize result        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;    }     // Driver Code    public static void Main()    {        int []arr = new int[] {8, 4, 2, 1};        int n = arr.Length;        Console.WriteLine("Inversion count : " +                           getInvCount(arr, n));    }} // This code is contributed by anuj_67.
<?php// A O(n^2) PHP program to// count inversions of size 3 // Returns count of// inversions of size 3function getInvCount($arr, $n){         // Initialize result    $invcount = 0;     for ($i = 1; $i < $n - 1; $i++)    {                 // Count all smaller elements        // on right of arr[i]        $small = 0;        for($j = $i + 1; $j < $n; $j++)            if ($arr[$i] > $arr[$j])                $small++;         // Count all greater elements        // on left of arr[i]        $great = 0;        for($j = $i - 1; $j >= 0; $j--)            if ($arr[$i] < $arr[$j])                $great++;         // Update inversion count by        // adding all inversions        // that have arr[i] as        // middle of three elements        $invcount += $great * $small;    }     return $invcount;}     // Driver Code    $arr = array(8, 4, 2, 1);    $n = sizeof($arr);    echo "Inversion Count : "        , getInvCount($arr, $n); // This code is contributed m_kit?>
<script>// A simple Javascript implementation  to count inversion of size 3     // returns count of inversion of size 3    function getInvCount(arr, n)    {        let invcount = 0; // initialize result                   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;    }         // driver program to test above function    let arr = [8, 4, 2, 1];    let n = arr.length;    document.write("Inversion count : " +                    getInvCount(arr, n));         // This code is contributed by rag2127      </script>
Output:
Inversion Count : 4 
Time complexity of this approach is : O(n^3)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++
Java
Python3
C#
PHP
Javascript
// A O(n^2) C++  program to count inversions of size 3#include<bits/stdc++.h>using namespace std; // Returns count of inversions of size 3int getInvCount(int arr[], int n){    int invcount = 0;  // Initialize result     for (int i=1; i<n-1; i++)    {        // Count all smaller elements on right of arr[i]        int small = 0;        for (int j=i+1; j<n; j++)            if (arr[i] > arr[j])                small++;         // Count all greater elements on left of arr[i]        int great = 0;        for (int j=i-1; j>=0; j--)            if (arr[i] < arr[j])                great++;         // Update inversion count by adding all inversions        // that have arr[i] as middle of three elements        invcount += great*small;    }     return invcount;} // Driver program to test above functionint main(){    int arr[] = {8, 4, 2, 1};    int n = sizeof(arr)/sizeof(arr[0]);    cout << "Inversion Count : " << getInvCount(arr, n);    return 0;}
// A O(n^2) Java  program to count inversions of size 3 class Inversion {         // returns count of inversion of size 3    int getInvCount(int arr[], int n)    {        int invcount = 0; // initialize result                 for (int i=0 ; i< n-1; i++)        {            // count all smaller elements on right of arr[i]            int small=0;            for (int j=i+1; j<n; j++)                if (arr[i] > arr[j])                    small++;                                 // count all greater elements on left of arr[i]            int great = 0;            for (int j=i-1; j>=0; j--)                        if (arr[i] < arr[j])                            great++;                                 // update inversion count by adding all inversions            // that have arr[i] as middle of three elements            invcount += great*small;        }        return invcount;    }    // driver program to test above function    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));    }} // This code has been contributed by Mayank Jaiswal
# A O(n^2) Python3 program to#  count inversions of size 3 # Returns count of inversions# of size 3def getInvCount(arr, n):     # Initialize result    invcount = 0       for i in range(1,n-1):             # Count all smaller elements        # on right of arr[i]        small = 0        for j in range(i+1 ,n):            if (arr[i] > arr[j]):                small+=1         # Count all greater elements        # on left of arr[i]        great = 0;        for j in range(i-1,-1,-1):            if (arr[i] < arr[j]):                great+=1         # Update inversion count by        # adding all inversions that        # have arr[i] as middle of        # three elements        invcount += great * small         return invcount # Driver program to test above functionarr = [8, 4, 2, 1]n = len(arr)print("Inversion Count :",getInvCount(arr, n)) # This code is Contributed by Smitha Dinesh Semwal
// A O(n^2) Java program to count inversions// of size 3using System; public class Inversion {         // returns count of inversion of size 3    static int getInvCount(int []arr, int n)    {        int invcount = 0; // initialize result                 for (int i = 0 ; i < n-1; i++)        {                         // count all smaller elements on            // right of arr[i]            int small = 0;            for (int j = i+1; j < n; j++)                if (arr[i] > arr[j])                    small++;                                 // count all greater elements on            // left of arr[i]            int great = 0;            for (int j = i-1; j >= 0; j--)                        if (arr[i] < arr[j])                            great++;                                 // update inversion count by            // adding all inversions that            // have arr[i] as middle of            // three elements            invcount += great * small;        }                 return invcount;    }         // driver program to test above function    public static void Main()    {                 int []arr = new int[] {8, 4, 2, 1};        int n = arr.Length;        Console.WriteLine("Inversion count : "                       + getInvCount(arr, n));    }} // This code has been contributed by anuj_67.
<?php// A O(n^2) PHP program to count// inversions of size 3 // Returns count of// inversions of size 3function getInvCount($arr, $n){    // Initialize result    $invcount = 0;     for ($i = 1; $i < $n - 1; $i++)    {        // Count all smaller elements        // on right of arr[i]        $small = 0;        for ($j = $i + 1; $j < $n; $j++)            if ($arr[$i] > $arr[$j])                $small++;         // Count all greater elements        // on left of arr[i]        $great = 0;        for ($j = $i - 1; $j >= 0; $j--)            if ($arr[$i] < $arr[$j])                $great++;         // Update inversion count by        // adding all inversions that        // have arr[i] as middle of        // three elements        $invcount += $great * $small;    }     return $invcount;} // Driver Code$arr = array (8, 4, 2, 1);$n = sizeof($arr);echo "Inversion Count : " ,      getInvCount($arr, $n);     // This code is contributed by m_kit?>
<script>// A O(n^2) Javascript  program to count inversions of size 3         // returns count of inversion of size 3    function getInvCount(arr, n)    {        let invcount = 0; // initialize result                  for (let i = 0 ; i < n - 1; i++)        {            // count all smaller elements on right of arr[i]            let small = 0;            for (let j = i + 1; j < n; j++)                if (arr[i] > arr[j])                    small++;                                  // count all greater elements on left of arr[i]            let great = 0;            for (let j = i - 1; j >= 0; j--)                    if (arr[i] < arr[j])                        great++;                                  // update inversion count by adding all inversions            // that have arr[i] as middle of three elements            invcount += great*small;        }        return invcount;    }         // driver program to test above function    let arr=[8, 4, 2, 1];    let n = arr.length;    document.write("Inversion count : " +getInvCount(arr, n));         // This code is contributed by avanitrachhadiya2155</script>
Output :
Inversion Count : 4 
Time Complexity of this approach : O(n^2)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 BITThe 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].
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].
jit_t
vt_m
ukasp
SHUBHAMSINGH10
rag2127
avanitrachhadiya2155
amartyaghoshgfg
Binary Indexed Tree
inversion
Advanced Data Structure
Arrays
Arrays
Binary Indexed Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Agents in Artificial Intelligence
Decision Tree Introduction with example
Disjoint Set Data Structures
Red-Black Tree | Set 2 (Insert)
AVL Tree | Set 2 (Deletion)
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews