Counting pairs while merge sorting
1 Pairs that stand in the wrong order
Eight children stand in a queue. The teacher wants them in order of height, with the shortest at the front. We number the children by height, 1 for the shortest and 8 for the tallest:
Child 8 stands ahead of child 1, so that pair is in the wrong order. A pair where a taller child stands ahead of a shorter one is an inversion. In an array, it is a pair of positions i < j with nums[i] > nums[j]. Two equal values are never an inversion.
A sorted queue has none. If the teacher swaps two neighbours at a time, each swap fixes exactly one inversion, so the count is also the number of swaps needed.
By hand, we count the shorter children behind each child:
| Child | 5 | 3 | 8 | 6 | 1 | 7 | 2 | 4 |
|---|---|---|---|---|---|---|---|---|
| Shorter ones behind | 4 | 2 | 5 | 3 | 0 | 2 | 0 | 0 |
That makes 16 inversions. In code, this is a loop inside a loop that checks every pair. At n = 10⁵ there are about 5 × 10⁹ pairs. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
Merge sort can count them while it sorts, in about n log n steps.
2 Every pair is split by one cut
Merge sort, from the lesson on merge sort and quick sort, cuts the array in the middle, sorts both halves, and merges them. We cut the queue the same way, into [5, 3, 8, 6] and [1, 7, 2, 4]. Every pair of children now falls into one of three kinds:
- Both in the left half. The recursive call on the left half counts these.
- Both in the right half. The call on the right half counts these.
- One in each half. These are cross pairs. Only the step that joins the two halves sees them.
So the count is a sum of three parts:
The recursive calls cut again and again, down to single children. A pair stays together until the first cut that falls between its two children. That cut counts it as a cross pair, and no other cut sees it. So every inversion is counted exactly once.
In each step, blue is the left side of a cut and orange the right side. The cuts count 12 + 2 + 2 = 16, the same as the count by hand.
3 Sorting the halves keeps the cross pairs
In a cross pair, the left child stands ahead of the right child, whatever order each half is in. So we can reorder the children inside a half, and the cross pairs stay the same.
This is why the count can ride on merge sort. By the time two halves are merged, the recursive calls have sorted them. Sorted halves make the cross pairs easy to count.
In a sorted left half, the values bigger than a right value always sit together at the end. For the right value 4, the left half [3, 5, 6, 8] has the block 5, 6, 8. Once we know where the block starts, we know its size without checking each value:
The same holds for every right value:
| Right value | Left values bigger | Count |
|---|---|---|
| 1 | 3, 5, 6, 8 | 4 |
| 2 | 3, 5, 6, 8 | 4 |
| 4 | 5, 6, 8 | 3 |
| 7 | 8 | 1 |
The counts add up to 12. The merge finds where each block starts at no extra cost.
4 Counting inside the merge
The merge keeps i at the front of the left half and j at the front of the right half. At each step, it moves the smaller of values[i] and values[j] into merged, and that pointer moves on.
When the right value is smaller, it goes ahead of values[i]. The left half is sorted, so it also goes ahead of every left value after i. Those are the values from i to mid, and each one makes an inversion with it:
When the left value is smaller or equal, it goes in and adds nothing. Its inversions were counted already, when the smaller right values went ahead of it.
Here is the top merge of our queue. Orange marks the value that moves, and blue marks the left values it passes:
The same merge as a table, with mid = 3:
| Step | i | j | Compare | Added | count |
|---|---|---|---|---|---|
| 1 | 0 | 4 | 1 < 3 | 3 − 0 + 1 = 4 | 4 |
| 2 | 0 | 5 | 2 < 3 | 3 − 0 + 1 = 4 | 8 |
| 3 | 0 | 6 | 3 ≤ 4 | 0 | 8 |
| 4 | 1 | 6 | 4 < 5 | 3 − 1 + 1 = 3 | 11 |
| 5 | 1 | 7 | 5 ≤ 7 | 0 | 11 |
| 6 | 2 | 7 | 6 ≤ 7 | 0 | 11 |
| 7 | 3 | 7 | 7 < 8 | 3 − 3 + 1 = 1 | 12 |
| 8 | 3 | done | right used up | 0 | 12 |
Only the right values add to the count. They add 4, 4, 3 and 1, the same counts as the table of blocks in the last section.
5 The code, and what it costs
countInversions copies nums into values and sorts the copy, so the caller's array stays as it was. sortAndCount(values, lo, hi) sorts the part from lo to hi and returns the inversions inside it: the left half's count, plus the right half's, plus what the merge counts.
mergeAndCount is the merge from the merge sort lesson, plus a count and the line that adds mid − i + 1.
C++
long long for every count. That means count and the return type of both helpers. vector<int> values = nums; makes a full copy, so sorting values leaves nums alone.
long for every count. That means count and the return type of both helpers. nums.clone() makes the copy. int[] values = nums; would only give the same array a second name.
No overflow to watch. Python's integers grow as needed. list(nums) makes the copy. values = nums would only give the same list a second name.
No overflow here. Numbers stay exact up to about 9 × 10¹⁵, so a count of 5 × 10⁹ is safe. [...nums] makes the copy.
The count is an int64, as the problem asks, so mid - i + 1 is converted with int64(...). values := nums would share the same array, so we make a new slice and copy into it.
The count is an i64. mid - i + 1 is a usize, so it needs as i64. The function owns nums, so sorting it does not touch the caller's vector. The n < 2 check keeps n - 1 from going below 0.
long for every count. That means count and the return type of both helpers. Clone() makes the copy, and returns an object, so it needs the (int[]) cast.
Our queue prints 16 in every language.
- Time: O(n log n). Counting adds at most one addition to each step of the merge, so the cost stays merge sort's: about n steps on each of about log n levels. At n = 10⁵ that is around 2 × 10⁶ steps, well inside the time limit.
- Space: O(n). The copy and
mergedeach hold up to n values. The call stack is only about log n frames deep. - The count needs 64 bits. A queue in reverse order has every pair wrong, about 5 × 10⁹ pairs at n = 10⁵. A 32-bit
intstops at about 2 × 10⁹.
6 When the condition is not the merge order
Reverse Pairs, in this section's problems, counts the pairs i < j with nums[i] > 2 × nums[j]. The split and the sorted halves still work. In a cross pair, the left value comes first whatever order the halves are in.
Counting inside the merge does not work. The merge moves a right value when it is smaller than the left value, but the question is whether the left value is more than double. Take the sorted halves [4, 9] and [2, 3]:
| Right value moves | Left values it passes | Real pairs, left > 2 × right |
|---|---|---|
| 2 | 4, 9 | only 9, since 4 is not more than 4 |
| 3 | 4, 9 | only 9, since 4 is less than 6 |
Counting the values passed gives 4, but the answer is 2.
So the count gets a walk of its own, before the merge. A pointer r starts at the front of the right half. For each left value, from smallest to largest, r moves on while the left value is more than double values[r]. Every right value that r has passed makes a pair with this left value, so we add r − (mid + 1).
The left values only grow. A bigger left value beats every right value that a smaller one beat. So r never moves back, and the walk takes about n steps per level, like the merge. The cost stays O(n log n). After the walk, the merge runs as usual, with no counting in it.
A pointer that only moves forward is the idea of the next topic, two pointers.
7 Mistakes and edge cases
- Counting on the wrong side. Adding the right values still waiting when a left value moves counts the pairs that are in order. On our top merge, it gives 4 instead of 12.
- Taking the right value on a tie. With
<in place of<=, an equal right value moves first and counts as an inversion. On [3, 3], the answer is 0, but this gives 1. - A 32-bit count. On 10⁵ values in falling order, the answer is 4,999,950,000. A 32-bit
intwraps around and returns a wrong value without any error. - Doubling in 32 bits. In the reverse-pairs check, 2 ×
values[r]can pass theintrange. On [2000000000, 1500000000], the double is 3 × 10⁹. It wraps around to a negative number, and the check counts a pair that does not exist. The safe form is2LL * values[r]. - Sorting the caller's array. Merge sort leaves the array sorted. If the caller still needs it, or the problem says not to change it, sort a copy, as our code does.
8 When to count while merging
The sign is a count of pairs where position matters: an earlier value against a later one, with n up to 10⁵. Checking every pair is n², so it gets TLE. Two shapes come up:
- A larger value before a smaller one. Count inside the merge, and add mid − i + 1 each time a right value moves first.
- Another condition, like more than double. If a bigger left value meets it whenever a smaller one does, count with a separate walk before each merge, then merge as usual.
Practice it
- Reverse PairsHard
- Count InversionsMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.