How Messy Is the Shelf
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
callNumbers = [112, 108, 130, 125, 101]
6
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.
callNumbers = [205, 205, 199, 210]
2
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- Hint 1
Suppose the left and right halves are each sorted, like
[108, 112]and[101, 125, 130]. How many left-half books are bigger than 101? Can you tell without comparing 101 to each? - Hint 2
The left half is sorted, so once one left book is bigger than 101, every book after it is too. One comparison can count a whole block of pairs.
- Hint 3
That is the moment in merge sort's merge when a right-half book is taken before the remaining left-half books. How many left books are still waiting then?
- Hint 4
Run merge sort and return a count with each sorted half. Total = pairs inside the left half + pairs inside the right half + cross pairs. While merging, each time you take from the right (only when strictly smaller), add the number of items left in the left half. On ties take from the left, so equal books are not counted.
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.
How to solve it
Every out-of-order pair is inside the left half, inside the right half, or crosses the halves. Merge sort handles the first two by recursion, and the cross pairs come for free during the merge, because both halves are sorted by then.
Trace [112, 108, 130, 125, 101]. Split into [112, 108] and [130, 125, 101].
- Left half: merging
[112]and[108], 108 is taken while 112 waits: +1. Result[108, 112], 1 pair. - Right half:
[125]and[101]give +1 and[101, 125]. Merging[130]with[101, 125]: 101 is taken while 130 waits (+1), then 125 (+1). Result[101, 125, 130], 3 pairs. - Top merge of
[108, 112]and[101, 125, 130]: 101 is taken while 108 and 112 both wait: +2 in one step. The rest come out with no more right-before-left moments. - Total: 1 + 3 + 2 = 6.
Step 3 is the trick: one comparison counted two pairs, since everything after 108 in a sorted half is at least 108. So add mid - i (all waiting left books), not 1. And on a tie take from the left, so equal call numbers never count.
function countOutOfOrder(callNumbers) {
const a = callNumbers.slice();
const tmp = new Array(a.length);
// sorts a[lo..hi) and returns the out-of-order pairs inside it
const sortCount = (lo, hi) => {
if (hi - lo < 2) return 0;
const mid = Math.floor((lo + hi) / 2);
let count = sortCount(lo, mid) + sortCount(mid, hi);
let i = lo, j = mid, k = lo;
while (i < mid && j < hi) {
if (a[i] <= a[j]) tmp[k++] = a[i++]; // ties go left: not out of order
else {
count += mid - i; // a[j] is smaller than every left book still waiting
tmp[k++] = a[j++];
}
}
while (i < mid) tmp[k++] = a[i++];
while (j < hi) tmp[k++] = a[j++];
for (let t = lo; t < hi; t++) a[t] = tmp[t];
return count;
};
return sortCount(0, a.length);
}def count_out_of_order(call_numbers):
# returns (sorted copy of books, out-of-order pairs inside it)
def sort_count(books):
if len(books) < 2:
return books, 0
mid = len(books) // 2
left, count_left = sort_count(books[:mid])
right, count_right = sort_count(books[mid:])
count = count_left + count_right
merged, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # ties go left: not out of order
merged.append(left[i])
i += 1
else:
count += len(left) - i # right[j] is smaller than every left book still waiting
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged, count
return sort_count(call_numbers)[1]Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.