Open In App

Count number of Inversion in a Binary Array

Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Array arr[], the task is to count the number of inversions in it. The number of inversions in an array is the number of pairs of indices i, j such that i < j and a[i] > a[j].

Examples:

Input: arr[] = {1, 0, 1, 0, 0, 1, 0}
Output: 8
Explanation: Pairs of the index (i, j) are (0, 1), (0, 3), (0, 4), (0, 6), (2, 3), (2, 4), (2, 6), (5, 6).

Input: arr[] = {0, 1}
Output: 0

Approach: Follow the below steps to solve the problem:

  • Initialize the variable count = 0, for storing the count of zeroes occur so far.
  • Ans, res = 0, for storing the number of inversions in an array.
  • Now, run a loop i from the last element of the array to the front.
  • And check, if arr[i] = 0, then, Increment count by 1.
  • Else, Add count in res.
  • Return res after executing the loop.

Below is the implementation of the above approach:

C++




// C++ code to implement the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number of
// inversions in the binary array
 
int solve(bool* arr, int N)
{
 
    // Initialize the variables
    int count = 0, res = 0;
 
    // Run a loop from back
    for (int i = N - 1; i >= 0; i--) {
 
        // arr[i] is 1
        if (arr[i]) {
            res += count;
        }
 
        // arr[i] is 0
        else {
            count++;
        }
    }
 
    // Return the resultant answer
    return res;
}
 
// Driver Code
int main()
{
 
    bool arr[] = { 1, 0, 1, 0, 0, 1, 0 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << solve(arr, N) << endl;
 
    bool arr2[] = { 1, 0 };
    int M = sizeof(arr2) / sizeof(arr2[0]);
    cout << solve(arr2, M) << endl;
    return 0;
}


Java




// Java code to implement the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function to count the number of
  // inversions in the binary array
  public static int solve(boolean[] arr, int N)
  {
 
    // Initialize the variables
    int count = 0, res = 0;
 
    // Run a loop from back
    for (int i = N - 1; i >= 0; i--) {
 
      // arr[i] is 1
      if (arr[i]) {
        res += count;
      }
 
      // arr[i] is 0
      else {
        count++;
      }
    }
 
    // Return the resultant answer
    return res;
  }
 
  public static void main(String[] args)
  {
    boolean[] arr = { truefalse, true, false,
                     false, truefalse };
    int N = arr.length;
    System.out.println(solve(arr, N));
 
    boolean[] arr2 = { true, false };
    int M = arr2.length;
    System.out.println(solve(arr2, M));
  }
}
 
// This code is contributed by lokesh.


Python3




# Python code for the above approach
# Function to count the number of
# inversions in the binary array
def solve(arr, N):
   
    # Initialize the variables
    count = 0
    res = 0
 
    # Run a loop from back
    for i in range(N-1, -1, -1):
        # arr[i] is 1
        if arr[i]:
            res += count
        # arr[i] is 0
        else:
            count += 1
 
    # Return the resultant answer
    return res
 
# Driver Code
arr1 = [1, 0, 1, 0, 0, 1, 0]
N = len(arr1)
print(solve(arr1, N))
 
arr2 = [1, 0]
M = len(arr2)
print(solve(arr2, M))
 
# This code is contributed by Potta Lokesh


C#




// C# code to implement the approach
using System;
using System.Collections.Generic;
 
public class Gfg {
 
    static int solve(int[] arr, int N)
    {
     
        // Initialize the variables
        int count = 0, res = 0;
     
        // Run a loop from back
        for (int i = N - 1; i >= 0; i--) {
     
            // arr[i] is 1
            if (arr[i]==1) {
                res += count;
            }
     
            // arr[i] is 0
            else {
                count++;
            }
        }
     
        // Return the resultant answer
        return res;
    }
     
    // Driver Code
    public static void Main(string[] args)
    {
     
        int[] arr = { 1, 0, 1, 0, 0, 1, 0 };
        int N = arr.Length;
        Console.WriteLine(solve(arr, N));
       
        //Console.WriteLine("\n");
        int[] arr2 = { 1, 0 };
        int M = arr2.Length;
        Console.WriteLine(solve(arr2, M));
    }
}
 
// This code is contributed by poojaagarwal2.


Javascript




// Function to count the number of
// inversions in the binary array
function solve(arr, N)
{
 
  // Initialize the variables
  let count = 0;
  let res = 0;
 
  // Run a loop from back
  for (let i = N - 1; i >= 0; i--) {
    // arr[i] is 1
    if (arr[i]) {
      res += count;
    }
    // arr[i] is 0
    else {
      count++;
    }
  }
 
  // Return the resultant answer
  return res;
}
 
// Test cases
console.log(solve([1, 0, 1, 0, 0, 1, 0], 7)); // Output: 4
console.log(solve([1, 0], 2)); // Output: 1
 
// This code is contributed by ksam24000


Output

8
1

Time Complexity: O(N)
Auxiliary Space: O(1)

Related Articles:



Last Updated : 13 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads