Count Inversions | Practice | GeeksforGeeks

Given an array of integers. Find the Inversion Count in the array. 
Inversion Count: For an array, inversion count indicates how far (or close) the array is from being sorted. If array is already sorted then the inversion count is 0. If an array is sorted in the reverse order then the inversion count is the maximum. 
Formally, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.
 
Example 1:
Input: N = 5, arr[] = {2, 4, 1, 3, 5}
Output: 3
Explanation: The sequence 2, 4, 1, 3, 5 
has three inversions (2, 1), (4, 1), (4, 3).
Example 2:
Input: N = 5
arr[] = {2, 3, 4, 5, 6}
Output: 0
Explanation: As the sequence is already 
sorted so there is no inversion count.
Example 3:
Input: N = 3, arr[] = {10, 10, 10}
Output: 0
Explanation: As all the elements of array 
are same, so there is no inversion count.
Your Task:
You don't need to read input or print anything. Your task is to complete the function inversionCount() which takes the array arr[] and the size of the array as inputs and returns the inversion count of the given array.

Expected Time Complexity: O(NLogN).
Expected Auxiliary Space: O(N).

Constraints:
1 ≤ N ≤ 5*105
1 ≤ arr[i] ≤ 1018
0
rudymendozain 48 minutes
if anyone can tell me why this does not work?long long int inversionCount(long long arr[], long long N){   // Your Code Here      vector<long long> sA;   unordered_map < long long , int> oldIndices;   long long arrCopy[N];      for(int i = 0 ; i < N; i++){       sA.push_back(arr[i]);       arrCopy[i] = arr[i];              oldIndices[ arr[i] ] = i ;   }               sort(sA.begin(), sA.end());      long long swaps = 0;      for(int newIdx = 0; newIdx < N; newIdx++){              //get my old idx       auto oldIdx = oldIndices[ sA[newIdx] ];               if(oldIdx != newIdx){           swaps++;                      //remove myself from the map           auto val = sA[newIdx];           oldIndices.erase( val);                                 //the displaced val gets my old idx           auto movedVal = arrCopy[newIdx];           oldIndices[ movedVal] = oldIdx;           arrCopy[oldIdx] = movedVal; //update our array                  }          }      return swaps;   }
0
jainatishay0721 day ago
This code is working fine but there is only memory error as thet want in O(n) and this code is in O(n^2) Space complexity.
def inversionCount(self, arr, n):
        i=0
        l=[]
        temp=0
        for i in range(n):
            temp=arr[i]
            for j in range(i+1,n):
                if temp>arr[j]:
                    l.append([temp,arr[j]])
        return len(l)
0
09himanshusah3 days ago
JavaScript Solution
class Solution {
    // Function to count inversions in the array.
    merge(arr,s,m,e) {
        let a1 = [];
        for(let i = s; i < m+1; i++) {
            a1.push(arr[i]);
        }
        let a2 = [];
        for(let i = m+1; i < e+1; i++) {
            a2.push(arr[i]);
        }
        let i = 0;
        let j = 0;
        let k = s;
        let count = 0;
        while(i < a1.length && j < a2.length) {
            if(a1[i] <= a2[j]) {
                arr[k++] = a1[i++];
            } else {
                arr[k++] = a2[j++];
                count += (m+1)-(s+i);
            }
        }
        while(i < a1.length) {
            arr[k++] = a1[i++];
        }
        while(j < a2.length) {
            arr[k++] = a2[j++];
        }
        return count;
    }
    mergesort(arr,s,e) {
        let cnt = 0;
        if(s < e) {
            let m = Math.floor(s+(e-s)/2);
            cnt += this.mergesort(arr,s,m);
            cnt += this.mergesort(arr,m+1,e);
            cnt += this.merge(arr,s,m,e);
        }
        return cnt;
    }
    inversionCount(arr, n)
    {
        //your code here
        let ans = this.mergesort(arr,0,n-1);
        return ans;
    }
}
0
vermaanshu20051 week ago
JAVA Solution  - Merger Sort Solution.
I have explained why many people are getting TLE despite writing the correct code.



class Solution
{
    static long inversionCount(long arr[], long N)
    {
        long b[] = new long[(int)N];// this is an imp step, creating arr at every place(in merge function)  is giving tle
     	return mergeSort(arr,b, 0, (int)(N - 1));
    }
    
    static long mergeSort(long arr[],long b[], int l, int r)
    {
        long count = 0l;
        if(l < r)
        {
            int mid = l + (r - l) / 2;
            
            count += mergeSort(arr,b, l, mid);
            count += mergeSort(arr,b, mid+1, r);
            
            count += merge(arr,b, l, mid, r);
        }
        return count;
    }
    
    static long merge(long arr[],long b[], int l, int m, int r)
    {
        long inv_count = 0l;
        
        int i = l;
        int j = m+1;
        int k = l;
        
        
        while(i <= m && j <= r)
        {
            if(arr[i] <= arr[j])
            {
               b[k++] = arr[i++];
            }
            else
            {
                b[k++] = arr[j++];
                inv_count = inv_count + (m - i + 1);
            }
            //k++;
        }
        
        while(i <= m)
        {
            b[k++] = arr[i++];
        }
        
        while(j <= r)
        {
            b[k++] = arr[j++];
        }
        
        for(i = (int)l; i<= r;i++)
        {
            arr[i] = b[i];
        }
        
        return inv_count;
    }
}
0
akshayausekar17981 week ago
hey guys i tried this code but it fails at 100th test
can any one elaborate the reason?
long long int inversionCount(long long arr[], long long N)
    {  
        long long min_ind = 0;
        long long max_ind = N-1;
        long long int count=0;    
        while(1){
            if(min_ind == N){
                break;
            }
            if(arr[min_ind] > arr[max_ind]){
            count++;
            }
            if(min_ind == max_ind){
                min_ind++;
                max_ind = N-1;
            }else{
                max_ind--;
            }
            
            
        }
        return count;
    }
 
0
aanchalsuntwal2 weeks ago
//Using insertion sort, but it fails at 100th test case.
long long sort(long long *a , long long n){   long long t,j,i,c=0;   for(i=0;i<n;i++)   {       t = a[i];       j = i-1;       while(j >= 0 && a[j] > t)       {           a[j+1]= a[j];           j--;           c++;       }       a[j+1] = t;   }   return c;}
long long int inversionCount(long long arr[], long long N){   // Your Code Here   long long r=0;   r = sort(arr,N);   return r;} 
0
gauravrastogi2 weeks ago
Getting segmentation fault why ??
// { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;


 // } Driver Code Ends
class Solution{
  public:
    // arr[]: Input Array
    // N : Size of the Array arr[]
    // Function to count inversions in the array.
    int merge(long long arr[],long long temp[],long long str,long long mid,long long end){
        long long inv_cnt=0,i=str,k=str,j=mid;
        while((i<=mid-1) && (j<=end)){
            if(arr[i]<=arr[j]){
                temp[k++]=arr[i++];
            }
            else{
                temp[k++]=arr[j++];
                inv_cnt = inv_cnt + (mid-i);
            }
        }
        while(i<=mid-1){
            temp[k++]=arr[i++];
        }
        while(j<=end){
            temp[k++]=arr[j++];
        }
        for(int i=str;i<=end;i++){
            arr[i]=temp[i];
        }
        return inv_cnt;
    }
    int mergeSort(long long arr[],long long temp[],long long str,long long end){
        long long inv_cnt=0;
        long long mid;
        while(str<end){
            mid=(str/end)/2;
            inv_cnt+=mergeSort(arr,temp,str,mid);
            inv_cnt+=mergeSort(arr,temp,mid+1,end);
            
            inv_cnt+=merge(arr,temp,str,mid,end);
        }
        return inv_cnt;
    }
    long long int inversionCount(long long arr[], long long N)
    {
        // Your Code Here
        long long inv_cnt=0;
        long long temp[N];
        inv_cnt += mergeSort(arr,temp,0,N-1);
        return inv_cnt;
    }

};
+2
shubham211019972 weeks ago
long long int inversionCount(long long arr[], long long n)   {       return mergeSort(arr,0,n-1);   }long long int mergeSort(long long arr[],long long low,long long high){    long long res=0;    if(low<high){      long long mid=(low+high)/2;        res+=mergeSort(arr,low,mid);        res+=mergeSort(arr,mid+1,high);        res+=merge(arr,low,mid,high);    }    return res;}long long merge(long long arr[],long long low,long long mid,long long high){    int n1=mid-low+1;    int n2=high-mid;    long long left[n1];    long long right[n2];    for(int  i=0;i<n1;i++){        left[i]=arr[i+low];    }    for(int i=0;i<n2;i++){        right[i]=arr[mid+1+i];    }   long long i=0,j=0,k=low,res=0;    while(i<n1 && j<n2){        if(left[i]<=right[j]){            arr[k]=left[i];            i++;            k++;        }        else{            res+=n1-i;            arr[k]=right[j];            j++;            k++;        }    }    while(i<n1){        arr[k++]=left[i++];    }    while(j<n2){        arr[k++]=right[j++];    }    return res;} 
0
shubham21101997
This comment was deleted.
0
sunboykenneth3 weeks ago
class Solution{
  private:
    long long int inversionCountImpl(long long arr[], int startIndex, int n, long long auxArr[]) {
        if (n < 2) {
            return 0;
        }
        
        int endIndex = startIndex + n - 1;
        int midIndex = (startIndex + endIndex) / 2;
        
        long long int leftPartInvCnt = inversionCountImpl(arr, startIndex, midIndex - startIndex + 1, auxArr);
        long long int rightPartInvCnt = inversionCountImpl(arr, midIndex + 1, endIndex - midIndex, auxArr);
        
        // Merge Sort
        long long int invCntInc = 0;
        int curAuxIndex = startIndex, leftIndex = startIndex, rightIndex = midIndex + 1;
        while (leftIndex <= midIndex && rightIndex <= endIndex) {
            if (arr[leftIndex] <= arr[rightIndex]) {
                auxArr[curAuxIndex++] = arr[leftIndex++];
                continue;
            }
            
            auxArr[curAuxIndex++] = arr[rightIndex++];
            invCntInc += (midIndex - leftIndex + 1);
        }
        
        while (leftIndex <= midIndex) {
            auxArr[curAuxIndex++] = arr[leftIndex++];
        }
        
        while (rightIndex <= endIndex) {
            auxArr[curAuxIndex++] = arr[rightIndex++];
        }
        
        for (int i = 0; i < n; i++) {
            arr[startIndex + i] = auxArr[startIndex + i];
        }

        return leftPartInvCnt + rightPartInvCnt + invCntInc;
    }
    
  public:
    // arr[]: Input Array
    // N : Size of the Array arr[]
    // Function to count inversions in the array.
    long long int inversionCount(long long arr[], long long N)
    {
        if (N < 2) {
            return 0;
        }
        
        long long *auxArr = new long long[N];
        
        return inversionCountImpl(arr, 0, N, auxArr);
    }

};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.