AlgoFrames

Count inversions

Challenge · Write code · about 25 min

An inversion is a pair of indices i < j with nums[i] > nums[j]. Return the number of inversions in nums.

The largest tests have 50,000 values, so checking every pair (O(n²)) is too slow. Count the pairs while merge sort merges.

Example 1

Input:

[[2,4,1,3,5]]

Output:

3

The pairs are (2, 1), (4, 1) and (4, 3).

Example 2

Input:

[[1,2,3]]

Output:

0

Sorted input has no inversions.

Constraints

  • 0 ≤ nums.length ≤ 100,000
  • -1,000,000 ≤ nums[i] ≤ 1,000,000
  • The answer fits in a double without rounding.

Learn the idea first: Merge sort, a visual lesson.

More Merge sort problems