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 & Conquer

An 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

  1. Recursively split the array in half, just like Merge Sort, down to single elements.
  2. Recursively count inversions within the left half, and within the right half.
  3. 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.
  4. Sum: inversions in the left half + inversions in the right half + inversions found during the merge step.
  5. 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)).

Count InversionsO(n log n)
Merge-sort counting how many pairs are out of order as halves merge.
2
0
4
1
1
2
3
3
5
4
Step 1 / 19
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Split [0..4] at 2
Python · Divide & Conquer in Code
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

BestO(n log n)
AverageO(n log n)
WorstO(n log n)
SpaceO(n) — auxiliary arrays for merging

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

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.