Count inversion

  • 2

    Inversion Count for an array indicates – how far (or close) the array is from being sorted.

    If array is already sorted then inversion count is 0. If array is sorted in reverse order that inversion count is the maximum.

    Formally speaking, two elements a[i] and a[j] form an inversion if a[i] > a[j] and i < j.

    For example,
    The sequence 2, 4, 1, 3, 5 has three inversions (2, 1), (4, 1), (4, 3).

  • 1

    modify mergesort a little bit and we will find number of inversions

  • 2

    Yeah I think this question is identical to

    327. Count of Range Sum 


    315. Count of Smaller Numbers After Self

  • 0

    Prove the following Lemma and you will know how to count inversion using merge sort.

    Lemma: The number of inversion in array A[1..n] equals the number of inversion in array A[1..m] plus the number of inversion in array A[m+1..n] plus the number of inversion in array Sort(A[1..m]) + Sort(A[m+1..n]).

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.