Skip to the code
cf.
+50 XP

#690 Count Out-of-Order Pairs in a Ranking

hard

A data table shows how far its current row order is from sorted. ranking[i] is the value in row i. Every pair of rows where a bigger value sits above a smaller one is "out of order", and the number of such pairs is exactly how many swaps of neighboring rows it would take to sort the table ascending.

Write outOfOrder(ranking) that returns the number of pairs i < j with ranking[i] > ranking[j]. Equal values are not out of order. Scores can be very large or negative.

Example 1

Input: ranking = [3,1,2]
Output: 2

3 is before both 1 and 2, which are smaller: 2 pairs.

Example 2

Input: ranking = [1,2,3]
Output: 0

Already ascending: no pairs.

Constraints

  • 0 <= ranking.length <= 10^5
  • -10^9 <= ranking[i] <= 10^9
  • The answer fits in a JavaScript number.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

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