VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-inversions-in-a-permutation-of-first-n-natural-numbers/

⇱ Count inversions in a permutation of first N natural numbers - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count inversions in a permutation of first N natural numbers

Last Updated : 23 Jul, 2025

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:


Output: 
3

 

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


 

Comment