Algorithms · Visualized
Count Inversions
Divide & Conquer
Break a problem into independent subproblems, solve each, and combine the answers.
An inversion is a pair of elements that are 'out of order' (earlier index has a bigger value than a later index). Time: O(n log n) average, O(n log n) worst; space: O(n) — auxiliary arrays for merging.
Big-O: Classic D&C recursions: Merge Sort, Quick Sort, Maximum Subarray, Fast Power.
Count Inversions
Divide & ConquerAn inversion is a pair of elements that are 'out of order' (earlier index has a bigger value than a later index). Counting all inversions naively takes O(n²), but a modified Merge Sort counts them during the merge step in O(n log n) — every time an element from the right half is merged in before an element from the left half, it forms inversions with all remaining left-half elements.
How Count Inversions Works
- Recursively split the array in half, just like Merge Sort, down to single elements.
- Recursively count inversions within the left half, and within the right half.
- While merging the two sorted halves back together, whenever you take an element from the right half before an element from the left half, that right-half element is 'inverted' with every remaining element in the left half — add that count.
- Sum: inversions in the left half + inversions in the right half + inversions found during the merge step.
- Return this total, along with the merged sorted array for use one level up.
Count Inversions Worked Example
Input: [2, 4, 1, 3, 5]
Split into [2,4] and [1,3,5]. Left half [2,4] has 0 inversions (already ordered). Right half [1,3,5] has 0 inversions. Merging [2,4] and [1,3,5]: take 1 (from right) before 2 and 4 (from left) → +2 inversions. Take 2, take 3, take 4, take 5 — no more inversions during merge. Total inversions: 2 (pairs (2,1) and (4,1)).
def count_inversions(a):
def merge(lo, mid, hi):
i, j = lo, mid + 1
tmp = []
inv = 0
while i <= mid and j <= hi:
if a[i] <= a[j]:
tmp.append(a[i]); i += 1
else:
tmp.append(a[j]); j += 1
inv += mid - i + 1
tmp += a[i:mid + 1] + a[j:hi + 1]
a[lo:hi + 1] = tmp
return inv
def sort(lo, hi):
if lo >= hi:
return 0
mid = (lo + hi) // 2
return sort(lo, mid) + sort(mid + 1, hi) + merge(lo, mid, hi)
return sort(0, len(a) - 1)Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Count Inversions Time & Space Complexity
When to Use Count Inversions
- Measuring how 'unsorted' a list is, e.g. for ranking comparison (how different are two people's movie rankings?).
- Collaborative filtering and recommendation systems that compare orderings.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.