Java Array Program · A41
Count Inversions in an Array in Java
An inversion is a pair that is out of order. Merge sort finds them in bulk: when a value from the right half wins, it is smaller than every value still waiting in the left half.
Problem Statement
Given an array of integers, count the pairs of positions i < j with arr[i] > arr[j].
A sorted array has 0 inversions; a strictly decreasing array of length n has n(n - 1) / 2. The count is returned as a long.
Input/Output Examples
[5, 3, 8, 1]Output4Explanation: (5, 3), (5, 1), (3, 1) and (8, 1).[1, 2, 3]Output0Explanation: no pair is out of order.[3, 2, 1]Output3Explanation: every pair is out of order: 3 × 2 / 2 = 3.Visual Explanation
- Halvesleft53right81each half: 1 and 1 inversion
- Sorted halvesleft35right18merge them
- 1 winscount+21 < 3 and 5 2 cross inversions
- Total1 + 1 + 24
[5, 3, 8, 1]: each half contributes its own inversions, and when 1 from the right half is merged first, it forms an inversion with both remaining left values (amber).Because both halves are sorted during the merge, one comparison accounts for a whole group of inversions at once: mid - i + 1 of them.
Approaches
Merge sort counts inversions in O(n log n). The brute force checks every pair.
Approach 1: Count During Merge Sort (Recommended)
Idea: sort a copy with merge sort; whenever the right element is smaller, add the number of remaining left elements.
- Recursively count inversions in each half.
- Merge the halves; when
a[j] < a[i], addmid - i + 1. - Return the sum of the three counts.
Time: O(n log n) · Space: O(n).
Approach 2: Check Every Pair
Idea: compare every pair i < j.
- Loop over
i. - Loop over
j > i. - Count pairs with
arr[i] > arr[j].
Time: O(n²) · Space: O(1).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Count During Merge Sort (Recommended)
The input is copied first, so the caller's array is not sorted as a side effect.
import java.util.Arrays;
public class InversionsMergeSort {
// While merging, every time a right-half value wins, it is smaller than all values left in the left half
static long countInversions(int[] arr) {
int[] a = arr.clone();
return sort(a, new int[a.length], 0, a.length - 1);
}
private static long sort(int[] a, int[] tmp, int lo, int hi) {
if (lo >= hi) {
return 0;
}
int mid = lo + (hi - lo) / 2;
long count = sort(a, tmp, lo, mid) + sort(a, tmp, mid + 1, hi);
int i = lo, j = mid + 1, k = lo;
while (i <= mid && j <= hi) {
if (a[i] <= a[j]) {
tmp[k++] = a[i++];
} else {
count += mid - i + 1; // a[j] is smaller than a[i..mid]
tmp[k++] = a[j++];
}
}
while (i <= mid) {
tmp[k++] = a[i++];
}
while (j <= hi) {
tmp[k++] = a[j++];
}
System.arraycopy(tmp, lo, a, lo, hi - lo + 1);
return count;
}
public static void main(String[] args) {
int[][] inputs = {{5, 3, 8, 1}, {1, 2, 3}, {3, 2, 1}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + countInversions(arr));
}
}
}
[5, 3, 8, 1] -> 4 [1, 2, 3] -> 0 [3, 2, 1] -> 3
Time complexity: O(n log n) · Space complexity: O(n).
Approach 2: Check Every Pair
The definition, written as code; it checks the merge-sort version.
import java.util.Arrays;
public class InversionsBrute {
// Checks every pair i < j: O(n^2)
static long countInversions(int[] arr) {
long count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
count++;
}
}
}
return count;
}
public static void main(String[] args) {
int[][] inputs = {{5, 3, 8, 1}, {1, 2, 3}, {3, 2, 1}};
for (int[] arr : inputs) {
System.out.println(Arrays.toString(arr) + " -> " + countInversions(arr));
}
}
}
[5, 3, 8, 1] -> 4 [1, 2, 3] -> 0 [3, 2, 1] -> 3
Time complexity: O(n²) · Space complexity: O(1).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Count During Merge Sort | O(n log n) | O(n) |
| Check Every Pair | O(n²) | O(1) |
Here n is the number of elements. Merge sort has log n levels of linear merging; the brute force examines n(n - 1) / 2 pairs.
Interview Tips and Recommended Approach
- Use
≤when merging. Equal values are not inversions. - Use
long. The count can reach aboutn² / 2. - Explain the bulk count. It is the key insight that makes the algorithm fast.
- Know the alternative. A Fenwick tree also counts inversions in
O(n log n).
Recommended Approach: Count During Merge Sort
Why: it reuses a standard sorting algorithm and adds one line to count inversions in bulk, reaching O(n log n).