Skip to the code
+50 XP

#193 Count Out-of-Order Rankings

hard

A sorting quiz asks players to drag items into order. To score an answer, the app counts how many pairs are backwards: pairs of positions i < j where ranks[i] > ranks[j].

Write countBackwardPairs(ranks) that returns that number. Lists can have up to 400,000 items, so checking every pair is too slow; aim for O(n log n). Equal values do not form a backwards pair.

Example 1

Input: ranks = [2,4,1,3,5]
Output: 3

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

Example 2

Input: ranks = [1,2,3,4]
Output: 0

A sorted list has no backwards pairs.

Constraints

  • 0 <= ranks.length <= 4 * 10^5
  • -10^9 <= ranks[i] <= 10^9
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).