Counting pairs while merge sorting

Video lessonComing soon

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:

53861724
The queue, front on the left. Child 8 stands ahead of child 1

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:

Child53861724
Shorter ones behind42530200

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:

inversions = left + right + cross

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.

Which cut counts which inversions
5031826314752647
Top cut: 12 inversions cross it, like 8 before 1

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.

5031826314752647
The halves as they stand: 12 cross inversions
3051628314254677
Each half sorted: still 12

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:

3051628314254677
The right value 4, and the block of left values bigger than it

The same holds for every right value:

Right valueLeft values biggerCount
13, 5, 6, 84
23, 5, 6, 84
45, 6, 83
781

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:

count += mid − i + 1

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:

Merging [3, 5, 6, 8] with [1, 2, 4, 7]
3051628314254677ij
values
101234567
1 < 3: 1 passes 4 values. count = 4

The same merge as a table, with mid = 3:

StepijCompareAddedcount
1041 < 33 − 0 + 1 = 44
2052 < 33 − 0 + 1 = 48
3063 ≤ 408
4164 < 53 − 1 + 1 = 311
5175 ≤ 7011
6276 ≤ 7011
7377 < 83 − 3 + 1 = 112
83doneright used up012

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 merged each 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 int stops 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 movesLeft values it passesReal pairs, left > 2 × right
24, 9only 9, since 4 is not more than 4
34, 9only 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).

Counting [4, 9] against [2, 3], mid = 1
40912233ir
4 > 2 × 2 is false: r stays, 4 adds 0

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 int wraps around and returns a wrong value without any error.
  • Doubling in 32 bits. In the reverse-pairs check, 2 × values[r] can pass the int range. 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 is 2LL * 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.
Before writing a loop inside a loop to count pairs, ask whether the pairs can be split into left, right and cross, and whether sorted halves make the cross pairs a block to count at once.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.