Skip to content
BytePatterns

Count Out-of-Order Pairs

HardSorting#merge-sort#divide-and-conquer#inversion-count~35m

Problem

A ranking service measures how far a user's list is from sorted by counting inverted pairs: positions i < j where nums[i] > nums[j]. Given a list of up to 100,000 integers, return that count. Equal values never form a pair. Comparing every pair would take about five billion steps at the upper limit, so the count has to come out of an O(n log n) process.

Examples

Input:  nums = [2, 4, 1, 3, 5]
Output: 3
Why:    (2, 1), (4, 1) and (4, 3)
Input:  nums = [5, 4, 3, 2, 1]
Output: 10
Why:    fully reversed, every one of the 5 × 4 / 2 pairs is inverted
Input:  nums = [1, 1, 1]
Output: 0
Why:    edge case, equal values are not out of order

Hints

0 / 3

Stuck on the idea rather than the code? Merge Sort covers it.