The Wayback Machine - https://web.archive.org/web/20210601082816/https://www.geeksforgeeks.org/count-inversions-in-a-permutation-of-first-n-natural-numbers/
Skip to content
Related Articles

Related Articles

Count inversions in a permutation of first N natural numbers
  • Last Updated : 01 Jun, 2021

Given an array, arr[] of size N denoting a permutation of numbers from 1 to N, the task is to count the number of inversions in the array.
Note: Two array elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.

Examples:

Input: arr[] = {2, 3, 1, 5, 4}
Output: 3
Explanation: Given array has 3 inversions: (2, 1), (3, 1), (5, 4).

Input: arr[] = {3, 1, 2}
Output: 2
Explanation: Given array has 2 inversions: (3, 1), (3, 2).

Different methods to solve inversion count has been discussed in the following articles:  



Approach: This problem can be solved by using binary search. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++14




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to count number of inversions in
// a permutation of first N natural numbers
int countInversions(int arr[], int n)
{
    vector<int> v;
  
    // Store array elements in sorted order
    for (int i = 1; i <= n; i++) {
        v.push_back(i);
    }
  
    // Store the count of inversions
    int ans = 0;
  
    // Traverse the array
    for (int i = 0; i < n; i++) {
  
        // Store the index of first
        // occurrence of arr[i] in vector V
        auto itr = lower_bound(
            v.begin(), v.end(), arr[i]);
  
        // Add count of smaller elements
        // than current element
        ans += itr - v.begin();
  
        // Erase current element from
        // vector and go to next index
        v.erase(itr);
    }
  
    // Print the result
    cout << ans;
  
    return 0;
}
  
// Driver Code
int main()
{
  
    // Given Input
    int arr[] = { 2, 3, 1, 5, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function Call
    countInversions(arr, n);
  
    return 0;
}
Output:
3

Time Complexity: O(N*log(N))
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :