Given an array of integers nums, return the number of inversions in the array.
An inversion is a pair of indices (i, j) such that i < j and nums[i] > nums[j].
The inversion count measures how far the array is from being sorted. A sorted array has zero inversions, and an array in strictly decreasing order has the most possible, n(n−1)/2 for an array of length n.
Function Signature
def count_inversions(nums: list[int]) -> int:
Rules
-
Only a strictly larger earlier element counts. Two equal values never form an inversion, whatever their positions.
-
Return the exact count as an integer. For the largest inputs it can reach 4,999,950,000, which does not fit in a 32-bit integer.
Constraints
-
1 <= len(nums) <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [2, 4, 1, 3, 5]
Output: 3
The inversions are at index pairs (0, 2), (1, 2) and (1, 3), which hold the values (2, 1), (4, 1) and (4, 3). No other earlier element is larger than a later one.
Input: nums = [5, 4, 3, 2, 1]
Output: 10
The array is strictly decreasing, so every pair of indices is an inversion: 4 pairs start at the 5, 3 at the 4, 2 at the 3 and 1 at the 2, for 10 in total.
Input: nums = [3, 1, 3, 1]
Output: 3
The inversions are at index pairs (0, 1), (0, 3) and (2, 3). The pairs (0, 2) and (1, 3) hold equal values, so they do not count.