Counting inversions
30 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)By adapting merge sort, we count all inversions in O(n log n) time instead of quadratic brute force.
What is an inversion?
An inversion is a pair of positions (i, j) with i < j where array[i] > array[j]. The more inversions an array has, the further it is from sorted.
An inversion is a pair of positions where the earlier value is bigger than the later one. The program below counts them by checking every pair.
- Define index i < j.
- Check whether array[i] > array[j].
- If true, count the pair as an inversion.
Example 1 · Brute force: check every pair (O(n²) time, O(1) space)
public class BruteForceInversionsDemo { public static long countInversions(int[] arr) { long count = 0; int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] > arr[j]) { count++; } } } return count; }
public static void main(String[] args) { int[] nums = {8, 4, 2, 1}; System.out.println("Total inversions: " + countInversions(nums)); }}Total inversions: 6
What this code does
- Two nested loops look at every pair (i, j), which is n × (n - 1) / 2 pairs. That is why 100,000 items would need billions of checks.
- Nested loops inspect all n * (n - 1) / 2 pairs pairwise.
- Array of size 4 in reverse order produces 6 inversions.
- Runs in O(n²) time, serving as a ground truth baseline.
In simple terms, an inversion represents two elements that are out of order relative to each other. Why is inversion count significant? A sorted array has zero inversions. A reverse-sorted array has the maximum n * (n - 1) / 2 inversions. The number of inversions directly quantifies the disorder or entropy of an array. Brute force checks every possible pair (i, j) with nested loops, taking quadratic O(n²) time. For an array of 100,000 items, checking all pairs requires 5 billion iterations, which is unacceptably slow. Adapting merge sort calculates the total inversion count in optimal O(n log n) time. Consider tracing inversions on array [8, 4, 2, 1]: For 8 at index 0: pairs are (8, 4), (8, 2), and (8, 1), giving 3 inversions. For 4 at index 1: pairs are (4, 2) and (4, 1), giving 2 inversions. For 2 at index 2: pair is (2, 1), giving 1 inversion. Total inversions = 3 + 2 + 1 = 6. This matches 4 * 3 / 2 for a completely reversed array.
- Inversion definition: pair (i, j) where i < j and array[i] > array[j].
- Sorted array: exactly 0 inversions.
- Reversed array: maximum possible inversions, n * (n - 1) / 2.
Predict the output
Count the inversions
Read each snippet and pick what it prints.
Round 1 of 2
Counting inversions during the merge step
While merging, each time a right value is taken before the remaining left values, all of those left values form inversions with it. The program below adds them up in bulk.
Example 2 · Optimal: count while merging (O(n log n) time, O(n) space)
public class MergeSortInversionsDemo { public static long countInversions(int[] arr) { int[] aux = new int[arr.length]; return sortAndCount(arr, aux, 0, arr.length - 1); }
private static long sortAndCount(int[] arr, int[] aux, int low, int high) { if (low >= high) return 0; int mid = low + (high - low) / 2; long count = 0; count += sortAndCount(arr, aux, low, mid); count += sortAndCount(arr, aux, mid + 1, high); count += mergeAndCount(arr, aux, low, mid, high); return count; }
private static long mergeAndCount(int[] arr, int[] aux, int low, int mid, int high) { System.arraycopy(arr, low, aux, low, high - low + 1); int i = low, j = mid + 1; long count = 0; for (int k = low; k <= high; k++) { if (i > mid) arr[k] = aux[j++]; else if (j > high) arr[k] = aux[i++]; else if (aux[i] <= aux[j]) arr[k] = aux[i++]; else { arr[k] = aux[j++]; count += (mid - i + 1); } } return count; }
public static void main(String[] args) { int[] nums = {8, 4, 2, 1}; System.out.println("Fast inversions count: " + countInversions(nums)); }}Fast inversions count: 6
What this code does
- The merge already compares left and right values, so counting adds no extra pass. One comparison adds mid - i + 1 inversions at once instead of checking each pair, which brings the cost down from n² to n log n.
- When aux[j] < aux[i], all (mid - i + 1) left elements are inverted with aux[j].
- Returns exact count 6 in O(n log n) time.
- Operates in place on input array while accumulating long counts.
During divide-and-conquer, inversions split into three disjoint categories. Inversions divide into left inversions, right inversions, and split inversions across both halves. Recursive calls return the counts for the left and right halves. The merge step counts all split inversions in linear O(n) time. When merging sorted left and right subarrays, suppose right element aux[j] is smaller than left element aux[i]. Because the left subarray is sorted, aux[j] is smaller than aux[i] and all remaining left elements. Therefore, taking aux[j] contributes exactly (mid - i + 1) inversions in a single constant-time step. No individual scanning of remaining left elements is required. Consider merging sorted left [4, 8] and sorted right [1, 2]: Left pointer i is at index 0 (value 4). Right pointer j is at index 2 (value 1). Mid is 0. Since 1 < 4, value 1 is inverted with both 4 and 8. Add mid - i + 1 = 0 - 0 + 1 = 2 inversions. Next, compare 4 and 2: since 2 < 4, add mid - i + 1 = 2 inversions. Total split inversions for this merge step is 2 + 2 = 4.
- Disjoint decomposition: left inversions + right inversions + split inversions.
- Bulk addition: when right[j] < left[i], add (mid - i + 1) to total count.
- Efficiency: piggybacks on merge sort comparisons with zero extra asymptotic cost.
Find the bug
Find the counting bug
Tap the line that counts wrongly.
A right value is taken before the left values still waiting.
Round 1 of 2Real-world ranking similarity and recommendation systems
Two rankings can be compared by counting inversions. The program below turns one user's ranking into positions in the other's and counts the disagreements.
Example 3 · Measuring user ranking similarity (O(n²) pair count)
import java.util.HashMap;import java.util.Map;
public class RankingSimilarityDemo { public static int rankingDistance(String[] userA, String[] userB) { Map<String, Integer> pos = new HashMap<>(); for (int i = 0; i < userA.length; i++) { pos.put(userA[i], i); } int[] mapped = new int[userB.length]; for (int i = 0; i < userB.length; i++) { mapped[i] = pos.get(userB[i]); }
// Count inversions in mapped array int inv = 0; for (int i = 0; i < mapped.length; i++) { for (int j = i + 1; j < mapped.length; j++) { if (mapped[i] > mapped[j]) inv++; } } return inv; }
public static void main(String[] args) { String[] user1 = {"MovieA", "MovieB", "MovieC", "MovieD"}; String[] user2 = {"MovieB", "MovieA", "MovieD", "MovieC"}; System.out.println("Kendall distance: " + rankingDistance(user1, user2)); }}Kendall distance: 2
What this code does
- Map stores user1 preference order as baseline indices [0, 1, 2, 3].
- user2 ranking maps to permutation [1, 0, 3, 2].
- Inversions are pairs (1, 0) and (3, 2), giving distance 2.
Suppose two users rank a list of movies from most favorite to least favorite. Converting user B's ranking relative to user A's ranking produces a permutation. The number of inversions in that permutation represents the Kendall tau distance between the two users. A distance of 0 indicates that both users have identical taste preferences. A maximum distance indicates completely opposite preferences. E-commerce websites use this metric to cluster similar customers and recommend personalized products. Measuring ranking distance in O(n log n) time allows real-time recommendation updates at scale. Trace ranking similarity between two users for items A, B, C: User 1 order: [A, B, C], labeled 1, 2, 3. User 2 order: [B, A, C], expressed in User 1's labels as [2, 1, 3]. Inversions in [2, 1, 3]: pair (2, 1) is inverted, giving inversion count 1. The users share high similarity with only a single rank discrepancy.
- Kendall tau distance: number of pairwise disagreements between two ranking lists.
- Recommendation clustering: users with low inversion distance share similar tastes.
- Algorithmic power: transforms a complex recommender metric into standard merge sort.
Next step
Check your understanding
10 quick questions