Count number of Inversion in a Binary Array
Last Updated :
13 Jan, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int solve( bool * arr, int N)
{
int count = 0, res = 0;
for ( int i = N - 1; i >= 0; i--) {
if (arr[i]) {
res += count;
}
else {
count++;
}
}
return res;
}
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
import java.io.*;
import java.util.*;
class GFG {
public static int solve( boolean [] arr, int N)
{
int count = 0 , res = 0 ;
for ( int i = N - 1 ; i >= 0 ; i--) {
if (arr[i]) {
res += count;
}
else {
count++;
}
}
return res;
}
public static void main(String[] args)
{
boolean [] arr = { true , false , true , false ,
false , true , false };
int N = arr.length;
System.out.println(solve(arr, N));
boolean [] arr2 = { true , false };
int M = arr2.length;
System.out.println(solve(arr2, M));
}
}
|
Python3
def solve(arr, N):
count = 0
res = 0
for i in range (N - 1 , - 1 , - 1 ):
if arr[i]:
res + = count
else :
count + = 1
return res
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))
|
C#
using System;
using System.Collections.Generic;
public class Gfg {
static int solve( int [] arr, int N)
{
int count = 0, res = 0;
for ( int i = N - 1; i >= 0; i--) {
if (arr[i]==1) {
res += count;
}
else {
count++;
}
}
return res;
}
public static void Main( string [] args)
{
int [] arr = { 1, 0, 1, 0, 0, 1, 0 };
int N = arr.Length;
Console.WriteLine(solve(arr, N));
int [] arr2 = { 1, 0 };
int M = arr2.Length;
Console.WriteLine(solve(arr2, M));
}
}
|
Javascript
function solve(arr, N)
{
let count = 0;
let res = 0;
for (let i = N - 1; i >= 0; i--) {
if (arr[i]) {
res += count;
}
else {
count++;
}
}
return res;
}
console.log(solve([1, 0, 1, 0, 0, 1, 0], 7));
console.log(solve([1, 0], 2));
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Related Articles:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...