Menu
CoddyTech

Count Inversions

Given a list of integers nums, return the number of inversions: pairs of indexes i < j with nums[i] > nums[j], a larger value before a smaller one. Equal values never form an inversion, and a sorted list has none.

Function

countInversions(nums: integer-array) → integer
numsinteger-array
the list of integers
Returnsinteger
the number of pairs i < j with nums[i] > nums[j]

Constraints

  • 1 ≤ nums.length ≤ 2 × 104
  • -104 ≤ nums[i] ≤ 104
  • The answer is at most n(n-1)/2 < 2 × 108, so it fits in a signed 32-bit integer.

Examples

Input
nums = [5, 3, 8, 1, 4]
Output
6
Explanation
5 comes before 3, 1 and 4: 3 pairs. 3 comes before 1, and 8 before 1 and 4: 3 more. 1 and 4 are in order, so the total is 6.
challenge icon

Follow-up

What changes if a pair only counts when nums[i] > 2 × nums[j]? Can merge sort still count those pairs in O(n log n)?

Reset code
def countInversions(nums):
    # Write code here

Test #1

Test #2

Test #3

Argument

nums = [5, 3, 8, 1, 4]

Expected Output

6