Aadil Hoda
Aadil Hoda

Reputation: 652

Wrong answer on Inversion count?

void merge(vector<int> arr, int l, int m, int r,int &count)
{
    int i, j, k;
    int n1 = m - l + 1;
    int n2 =  r - m;

    /* create temp arrays */
    vector<int> L, R;

    /* Copy data to temp arrays L[] and R[] */
    for (i = 0; i < n1; i++)
        L.push_back(arr[l+i]);
    for (j = 0; j < n2; j++)
        R.push_back(arr[m+1+j]);
     /* Merge the temp arrays back into arr[l..r]*/
    i = 0; // Initial index of first subarray
    j = 0; // Initial index of second subarray
    k = l; // Initial index of merged subarray
    while (i < n1 && j < n2)
    {
        if (L[i] <= R[j])
        {
            arr[k] = L[i];
            i++;
        }
        else
        {
            arr[k] = R[j];
            count+=(n1-i);
            j++;
        }
        k++;
    }

    /* Copy the remaining elements of L[], if there
       are any */
    while (i < n1)
    {
        arr[k] = L[i];
        i++;
        k++;
    }

    /* Copy the remaining elements of R[], if there
       are any */
    while (j < n2)
    {
        arr[k] = R[j];
        j++;
        k++;
    }
}

/* l is for left index and r is right index of the
   sub-array of arr to be sorted */
void mergeSort(vector<int> arr, int l, int r,int &count)
{
    if (l < r)
    {
        // Same as (l+r)/2, but avoids overflow for
        // large l and h
        int m = l+(r-l)/2;

        // Sort first and second halves
        mergeSort(arr, l, m,count);
        mergeSort(arr, m+1, r,count);

        merge(arr, l, m, r,count);
    }
}

int Solution::countInversions(vector<int> &A) {
    int count = 0;
    mergeSort(A,0,A.size()-1,count);
    return count;
}

This is my code for counting number of inversions. I have solved this question earliar also, so i am pretty confident about the logic i implemented, i dont know why it is not passing some of the test cases on interview Bit Test Cases. Any help will be appreciated!Thanks.

Your submission failed for the following input:

A : [ 84, 2, 37, 3, 67, 82, 19, 97, 91, 63, 27, 6, 13, 90, 63, 89, 100, 60, 47, 96, 54, 26, 64, 50, 71, 16, 6, 40, 84, 93, 67, 85, 16, 22, 60 ]

Your function returned the following :

372

The expected returned value :

290

Upvotes: 0

Views: 104

Answers (1)

Scott Hunter
Scott Hunter

Reputation: 49883

You are counting inversions at every level of the recursion; the question (apparently) is only interested in inversions in the input array.

If I apply your definition of an inversion to the input array, I get the expected return value.

Upvotes: 1

Related Questions