Skip to content
RED SAGSkills

Count Out-of-Order Pairs

A ranking system measures how far a list is from sorted. A pair of positions i < j is out of order when nums[i] > nums[j].

Return the number of out-of-order pairs. The large tests rule out checking every pair; count them while merge-sorting the list.

Example 1

Input: nums = [2,4,1,3,5]
Output: 3
Explanation: (2,1), (4,1) and (4,3).

Example 2

Input: nums = [5,4,3,2,1]
Output: 10
Explanation: Every pair is out of order: 4 + 3 + 2 + 1.

Constraints

  • 0 <= nums.length <= 4 * 10^4
  • -10^6 <= nums[i] <= 10^6
Hint 1

Split the list in half and count pairs inside each half recursively.

Hint 2

While merging, every time an element from the right half is taken before remaining left-half elements, it forms a pair with each of them.

Good practice for: Data Scientist, Data Engineer, Backend Developer, Machine Learning Engineer, Database Administrator

Run checks your code on 3 sample tests. Submit runs all 8 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.