Count Inversions with Merge Sort

medium
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 20. Everything before it counts as cleared.

An inversion is a pair i < j with a[i] > a[j]. The count measures how unsorted a list is: 0 for sorted, n(n−1)/2 for reversed.

Implement count_inversions(a) in O(n log n) by counting during merge sort: when an element from the right half is merged before elements still waiting in the left half, each of those forms an inversion.

Then use it for kendall_tau_distance(rank_a, rank_b): given two orderings of the same items (lists of item names), the number of item pairs they order differently.

#divide-and-conquer#sorting2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Count Inversions with Merge Sort · TechGradify