Open In App

Count number of Inversion in a Binary Array

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
1 Like
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++
Java Python3 C# JavaScript

Output
8
1

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

Related Articles:


Similar Reads