Count Inversions
Count pairs (i, j) with i < j but nums[i] > nums[j] — how far the array is from sorted.
Intuition
During a merge of two sorted halves, the moment you take an element from the right half before elements remain in the left half, that right element is smaller than all remaining left elements — that's a whole batch of inversions counted in one step.
Approach
Recurse on halves
Inversions = inversions inside left + inside right + cross inversions. The first two come from recursion.
Count during merge
Merging sorted halves: when right[j] < left[i], it jumps ahead of len(left) − i left elements — add that many inversions at once.
Why it's fast
Each merge is linear and there are log n levels → O(n log n), versus O(n²) brute force.
Solution & live demo
Edge cases
Right elements never jump ahead → 0 inversions.
Every pair inverts: n(n−1)/2, counted in batches.