Count Inversions
Pattern: Basic sorts
Count pairs i < j with nums[i] > nums[j] in O(n log n) by letting merge sort count them while it merges.
The problem
You are given an array of between 1 and 100,000 whole numbers. An inversion is a pair of positions i < j where
nums[i] > nums[j]: a bigger value that comes before a smaller one. Return how many inversions there are. For example,
[2, 4, 1, 3, 5] has three: (2, 1), (4, 1) and (4, 3). The count can be as large as about 5 × 10⁹, so return a 64-bit
number.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name countInversions and the limits are this guide's own. The function may reorder nums while counting.
Think first
- Count the inversions of
[2, 4, 1, 3, 5]by checking every pair. How many pairs is that for 100,000 numbers? - In a sorted array there are no inversions. Which sorting algorithm meets every out-of-order pair along the way?
- While merging
[2, 4]with[1], how many inversions does taking the 1 first reveal?
Hints
Brute force, and why it fails
Two nested loops that test every pair i < j are simple and correct, but O(n²). Bubble sort also makes exactly one swap
per inversion, so counting its swaps works too, and is just as slow.
The key insight
Merge sort already compares elements across the two halves in order. At the moment it takes a smaller value from the right half, all the remaining left-half values form inversions with it, so it can count a whole batch with one subtraction.
Dry run
| count | 0 |
|---|
nums = [2, 4, 1, 3, 5]. Split at the middle into the left part [2, 4, 1] and the right part [3, 5].
The plan
function sortAndCount(nums, low, high):
if low >= high:
return 0
mid = low + (high - low) div 2
count = sortAndCount(nums, low, mid) + sortAndCount(nums, mid + 1, high)
left = low, right = mid + 1
while left <= mid and right <= high:
if nums[left] <= nums[right]:
take nums[left], left = left + 1
else:
count = count + (mid - left + 1) # all waiting left values are bigger
take nums[right], right = right + 1
take the leftovers, copy the merged values back
return count
Complexity
- Time
O(n log n)- Space
O(n)
Merge sort's work, plus one addition per step taken from the right. The merge needs an O(n) temporary list.
Edge cases
- Sorted input: 0 inversions.
- Reversed input of length
n: every pair is inverted, so n(n - 1)/2. For 100,000 that is 4,999,950,000, which needs 64 bits. - Equal values are not inversions. Taking from the left on
<=makes sure they are not counted. - One element: 0.
I've built my logic, show the code
Java
class Solution {
public long countInversions(int[] nums) {
return sortAndCount(nums, 0, nums.length - 1);
}
private long sortAndCount(int[] nums, int low, int high) {
if (low >= high) {
return 0;
}
int mid = low + (high - low) / 2;
long count = sortAndCount(nums, low, mid) + sortAndCount(nums, mid + 1, high);
int[] merged = new int[high - low + 1];
int left = low;
int right = mid + 1;
int k = 0;
while (left <= mid && right <= high) {
if (nums[left] <= nums[right]) {
merged[k++] = nums[left++];
} else {
count += mid - left + 1; // nums[left..mid] are all bigger than nums[right]
merged[k++] = nums[right++];
}
}
while (left <= mid) {
merged[k++] = nums[left++];
}
while (right <= high) {
merged[k++] = nums[right++];
}
for (int i = 0; i < merged.length; i++) {
nums[low + i] = merged[i];
}
return count;
}
}C++
class Solution {
public:
long long countInversions(vector<int>& nums) {
return sortAndCount(nums, 0, static_cast<int>(nums.size()) - 1);
}
long long sortAndCount(vector<int>& nums, int low, int high) {
if (low >= high) {
return 0;
}
int mid = low + (high - low) / 2;
long long count = sortAndCount(nums, low, mid) + sortAndCount(nums, mid + 1, high);
vector<int> merged;
merged.reserve(high - low + 1);
int left = low;
int right = mid + 1;
while (left <= mid && right <= high) {
if (nums[left] <= nums[right]) {
merged.push_back(nums[left++]);
} else {
count += mid - left + 1; // nums[left..mid] are all bigger than nums[right]
merged.push_back(nums[right++]);
}
}
while (left <= mid) {
merged.push_back(nums[left++]);
}
while (right <= high) {
merged.push_back(nums[right++]);
}
for (int i = 0; i < static_cast<int>(merged.size()); i++) {
nums[low + i] = merged[i];
}
return count;
}
};Python
class Solution:
def countInversions(self, nums):
return self.sortAndCount(nums, 0, len(nums) - 1)
def sortAndCount(self, nums, low, high):
if low >= high:
return 0
mid = (low + high) // 2
count = self.sortAndCount(nums, low, mid) + self.sortAndCount(nums, mid + 1, high)
merged = []
left, right = low, mid + 1
while left <= mid and right <= high:
if nums[left] <= nums[right]:
merged.append(nums[left])
left += 1
else:
count += mid - left + 1 # nums[left..mid] are all bigger than nums[right]
merged.append(nums[right])
right += 1
merged.extend(nums[left:mid + 1])
merged.extend(nums[right:high + 1])
nums[low:high + 1] = merged
return countCommon mistakes
- Adding just 1 instead of
mid - left + 1when taking from the right. - Using
<instead of<=in the merge, which counts equal pairs as inversions. - Keeping the count in a 32-bit int, which overflows for large reversed inputs.