Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Count number of 1s in the array after N moves
Next article icon

Count number of Inversion in a Binary Array

Last Updated : 13 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
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 = { 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
 
 
Output
8 1

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

Related Articles:

  • Introduction to Arrays – Data Structures and Algorithms Tutorials


Next Article
Count number of 1s in the array after N moves
author
akashjha2671
Improve
Article Tags :
  • Arrays
  • DSA
  • Technical Scripter
  • Technical Scripter 2022
Practice Tags :
  • Arrays

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], [
    13 min read
  • Count inversions of size k in a given array
    Given an array of n distinct integers [Tex]a_{1}, a_{2}, ..., a_{n} [/Tex]and an integer k. Find out the number of sub-sequences of a such that [Tex]a_{i_{1}} > a_{i_{2}} > ... > a_{i_{k}} [/Tex], and [Tex]1 <= i_{1} < i_{2} < ... < i_{k} <= n [/Tex]. In other words output th
    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: 7 Input: arr[] = [0, 0, 0, 0, 0, 0,
    8 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
  • Count inversions in an array | Set 4 ( Using Trie )
    Inversion Count for an array indicates – how far (or close) the array is from being sorted. If the array is already sorted then inversion count is 0. If the array is sorted in reverse order that inversion count is the maximum. Two elements a[i] and a[j] form an inversion if a[i] > a[j] and i <
    12 min read
  • Inversion count in Array Using Self-Balancing BST
    Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. Note: The Inversion Count for an array indicates how far (or close) the array is from being sorted. If the array is already sorted
    14 min read
  • Counting inversions in an array using segment tree
    Given an array of integers arr, the task is to count the number of inversions in the array. If A[i] > A[j] and i < j then the pair (A[i], A[j]) is part of an inversion. Examples: Input: arr[] = {8, 4, 2, 1} Output: 6 Input: arr[] = {3, 1, 2} Output: 2 Approach: Build a segment tree where each
    10 min read
  • Invert actual bits of a number
    Given a non-negative integer n. The problem is to invert the bits of n and print the number obtained after inverting the bits. Note that the actual binary representation of the number is being considered for inverting the bits, no leading 0’s are being considered. Examples: Input : 11Output : 4(11)1
    13 min read
  • Javascript Program to Count 1's in a sorted binary array
    Given a binary array sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = {1, 1, 0, 0, 0, 0, 0} Output: 2 Input: arr[] = {1, 1, 1, 1, 1, 1, 1} Output: 7 Input: arr[] = {0, 0, 0, 0, 0, 0, 0} Output: 0A simple solution is to traverse the array linearly. The time comp
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences