How Messy Is the Shelf

HardsortingAlso known as Count Inversions

A library volunteer tidies shelves by one rule: she only ever swaps two books that stand next to each other. Each book has a call number, and the shelf is tidy when the numbers read in non-decreasing order from left to right. A library may own several copies of a book, so numbers can repeat.

Before she starts on a long shelf, the head librarian wants to know how many swaps the job will take. Call a pair of books out of order when the left one has a larger number than the right one. 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). Six pairs, so six neighbour swaps.

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

Each 205 sits left of the smaller 199: two pairs. The two copies of 205 are equal, so they do not count, and 210 is already where it belongs.

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 and count those with the left number larger. Simple and correct.

That is about n²/2 comparisons: 1.25 billion for 50,000 books. Simulating the volunteer's swaps (bubble sort) is just as slow, because a badly mixed shelf really does need 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