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++
// 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 = { 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));
}
}
// 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
Time Complexity: O(N)
Auxiliary Space: O(1)
Related Articles:
Similar Reads
Inversion count in Array using BIT Inversion Count for an array indicates â how far (or close) the array is from being sorted. If the array is already sorted then the inversion count is 0. If the array is sorted in the reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] > a[j] an
15+ min read
Count Subarrays of 1 in Binary Array Given an array arr[] of size N, the array contains only 1s and 0s, and the task is to return the count of the total number of subarrays where all the elements of the subarrays are 1. Examples: Input: N = 4, arr[] = {1, 1, 1, 0}Output: 6Explanation: Subarrays of 1 will look like the following: [1], [
12 min read
Count inversions of size k in a given array Given an array of n distinct integers a_{1}, a_{2}, ..., a_{n} and an integer k. Find out the number of sub-sequences of a such that a_{i_{1}} > a_{i_{2}} > ... > a_{i_{k}} , and 1 <= i_{1} < i_{2} < ... < i_{k} <= n . In other words output the total number of inversions of l
14 min read
Count 1's in a sorted binary array Given a binary array arr[] of size n, which is sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = [1, 1, 0, 0, 0, 0, 0]Output: 2Explanation: Count of the 1's in the given array is 2.Input: arr[] = [1, 1, 1, 1, 1, 1, 1]Output: 7Input: arr[] = [0, 0, 0, 0, 0, 0, 0]
7 min read
Count number of 1s in the array after N moves Given an array of size N in which initially all the elements are 0(zero). The task is to count the number of 1's in the array after performing N moves on the array as explained:In each move (starting from 1 to N) the element at the position of the multiple of the move number is changed from 0 to 1 o
9 min read