How Messy Is the Shelf

HardsortingAlso known as Count Inversions

A library volunteer tidies a shelf by only ever swapping two neighbouring books, until the call numbers read in non-decreasing order left to right (copies mean numbers can repeat). The head librarian wants to know how many swaps a long shelf will take. Call a pair out of order when the left book has the larger number. A useful neighbour swap fixes exactly one such pair and breaks none, so the job takes exactly as many swaps as there are out-of-order pairs.

Your task

Write countOutOfOrder(callNumbers). Return the number of index pairs i < j with callNumbers[i] > callNumbers[j]. Equal numbers are not out of order. An empty shelf returns 0.

Aim for O(n log n). With 50,000 books, checking every pair is too slow.

countOutOfOrder(callNumbers: int[]) → int

Examples

Example 1
Input
callNumbers = [112, 108, 130, 125, 101]
Output
6
Why

The out-of-order pairs are (112, 108), (112, 101), (108, 101), (130, 125), (130, 101) and (125, 101). There are six pairs, so the shelf needs six neighbour swaps.

Example 2
Input
callNumbers = [205, 205, 199, 210]
Output
2
Why

Each 205 sits to the left of the smaller 199, which gives two out-of-order pairs. The two equal 205s do not form a pair.

Constraints

  • 0 ≤ callNumbers.length ≤ 50,000
  • 1 ≤ callNumbers[i] ≤ 1,000,000
  • The answer fits in a normal integer (at most about 1.25 billion).
Start with brute force

Check every pair i < j: about n²/2 comparisons, 1.25 billion for 50,000 books. Simulating the swaps (bubble sort) is just as slow, because a badly mixed shelf really needs that many swaps. You want to count them without doing them.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code