Algo-Sim › Sorting & Divide and Conquer

Count Inversions

Hard · Sorting & Divide and Conquer · step through it in Java, Python and C++ on your own input

Count pairs i < j with nums[i] > nums[j] in O(n log n): merge sort, adding the size of the remaining left half whenever the right element wins.

Problem

An inversion is a pair of positions i < j with nums[i] > nums[j]. Return how many inversions nums contains; it measures how far the array is from sorted.

Constraints

Edge cases to test

Follow-up questions

What is the Fenwick tree alternative?
Scan left to right and count earlier values greater than each one with a Fenwick tree over value ranks: O(n log n).
Where is this used?
Measuring how far two rankings disagree (Kendall tau) and Count of Smaller Numbers After Self (LC 315).

Solution

Java

public long countInversions(int[] nums) {
    return sortCount(nums, new int[nums.length], 0, nums.length - 1);
}

private long sortCount(int[] nums, int[] tmp, int lo, int hi) {
    if (lo >= hi) return 0;
    int mid = (lo + hi) / 2;
    long count = sortCount(nums, tmp, lo, mid);
    count += sortCount(nums, tmp, mid + 1, hi);
    int i = lo, j = mid + 1, k = lo;
    while (i <= mid && j <= hi) {
        if (nums[i] <= nums[j]) tmp[k++] = nums[i++];
        else {
            count += mid - i + 1;
            tmp[k++] = nums[j++];
        }
    }
    while (i <= mid) tmp[k++] = nums[i++];
    while (j <= hi) tmp[k++] = nums[j++];
    for (k = lo; k <= hi; k++) nums[k] = tmp[k];
    return count;
}

Python

def count_inversions(nums):
    tmp = [0] * len(nums)

    def sort_count(lo, hi):
        if lo >= hi:
            return 0
        mid = (lo + hi) // 2
        count = sort_count(lo, mid)
        count += sort_count(mid + 1, hi)
        i, j, k = lo, mid + 1, lo
        while i <= mid and j <= hi:
            if nums[i] <= nums[j]:
                tmp[k] = nums[i]
                i += 1
            else:
                count += mid - i + 1
                tmp[k] = nums[j]
                j += 1
            k += 1
        while i <= mid:
            tmp[k] = nums[i]
            i, k = i + 1, k + 1
        while j <= hi:
            tmp[k] = nums[j]
            j, k = j + 1, k + 1
        for k in range(lo, hi + 1):
            nums[k] = tmp[k]
        return count

    return sort_count(0, len(nums) - 1)

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    long long countInversions(vector<int> &nums) {
        vector<int> tmp(nums.size());
        return sortCount(nums, tmp, 0, int(nums.size()) - 1);
    }

    long long sortCount(vector<int> &nums, vector<int> &tmp, int lo, int hi) {
        if (lo >= hi)
            return 0;
        int mid = (lo + hi) / 2;
        long long count = sortCount(nums, tmp, lo, mid);
        count += sortCount(nums, tmp, mid + 1, hi);
        int i = lo, j = mid + 1, k = lo;
        while (i <= mid && j <= hi) {
            if (nums[i] <= nums[j])
                tmp[k++] = nums[i++];
            else {
                count += mid - i + 1;
                tmp[k++] = nums[j++];
            }
        }
        while (i <= mid)
            tmp[k++] = nums[i++];
        while (j <= hi)
            tmp[k++] = nums[j++];
        for (k = lo; k <= hi; k++)
            nums[k] = tmp[k];
        return count;
    }
};

More Sorting & Divide and Conquer problems