LeetCode #493 Hard

Reverse Pairs

Reverse Pairs is LeetCode 493 (Hard). Count the pairs of indices (i, j) with i < j and nums[i] > 2 * nums[j].

  • nums holds up to 5 × 10^4 numbers, so checking all pairs, about 1.25 billion of them, is too slow.
  • Values cover the whole 32-bit range, so 2 * nums[j] does not fit in a 32-bit integer.
Constraints
  • 1 <= nums.length <= 5 * 10^4
  • -2^31 <= nums[i] <= 2^31 - 1
arraymerge-sortdivide-and-conquer
Open on LeetCode ↗
02

Intuition

Sort the array with merge sort and count during the merges. Any pair (i, j) is split by exactly one merge, the first one whose range contains both: i lands in its left half and j in its right half. Sorting inside a half never moves a number across the middle, so when that merge runs, i is still to the left of j.

With both halves sorted, one forward-only pointer counts every crossing pair. For a left value, the right values it beats form a prefix of the right half, and a bigger left value beats at least that prefix. So walk the left half in order and only ever push j forward.

How to spot this pattern

"Count pairs i < j where the left value beats some function of the right value" is merge sort counting: Count Inversions, Count of Smaller Numbers After Self and Count of Range Sum all count the crossing pairs between two sorted halves.

03

Approach

Try it first

Before reading on, take a left half [2, 4] and a right half [1, 3, 5], both sorted. Count the pairs with left > 2 × right using a pointer that never moves backwards. Then decide where that count goes inside merge sort. Aim for O(n log n).

1

Split and count each half

sort_count(lo, hi) returns the number of reverse pairs inside nums[lo:hi] and leaves that range sorted. It calls itself on both halves first; a range of one number has no pairs.

2

Sweep the pairs that cross the middle

Set j = mid. For each i in the left half, move j forward while nums[i] > 2 * nums[j], then add j - mid: that is how many right values this left value beats, all of them sitting before j.

3

Merge only after counting

Merge the two sorted halves into place: heapq.merge in Python, std::merge in C++, a two-pointer merge in Java. Counting has to come first, because once the halves are mixed you can no longer tell which numbers came from the left.

4

Add the three counts

Return the left-half count plus the right-half count plus the crossing count. reversePairs returns sort_count(0, n), the total for the whole array.

04

Code in Python, C++ and Java

▶1from heapq import merge
▶2 
▶3class Solution:
▶4 def reversePairs(self, nums):
▶5 def sort_count(lo, hi):
▶6 if hi - lo <= 1:
▶7 return 0
▶8 mid = (lo + hi) // 2
▶9 count = sort_count(lo, mid) + sort_count(mid, hi)
▶10 j = mid
▶11 for i in range(lo, mid):
▶12 while j < hi and nums[i] > 2 * nums[j]:
▶13 j += 1
▶14 count += j - mid
▶15 nums[lo:hi] = merge(nums[lo:mid], nums[mid:hi])
▶16 return count
▶17 
▶18 return sort_count(0, len(nums))
array13231checkpairs0split in halves until each piece holds one number
nums[1, 3, 2, 3, 1]5 numbers
A pair with i before j either lies inside one half or has i in the left half and j in the right half. The halves are counted by the recursive calls, so each merge only counts the pairs that cross its middle, while both halves are sorted.
array13231ijleftrightcheck1left value≤6twice 3pairs01 is not more than twice 3 → stop, add 0
pairs for 10right values passed
total0
1 is not more than 6, so 3 and everything after it are too big to pair with 1. No right value is before j, so 1 adds nothing. That was the last left value of this merge.
array13231merged, sortedcheckpairs0merge the halves into sorted order
range[1, 3]now sorted
Counting is done for this range, so merge the two sorted halves. The parent call needs this range sorted to run the same forward-only sweep one level up. Values moving around inside it is fine: any pair counted later crosses a higher middle, and both of its numbers stay on their own side.
array13231ijleftrightcheck3left value>2twice 1pairs03 is more than twice 1 → j moves on
left3
right1twice is 2
3 > 2, so 1 forms a pair with 3. j steps past it. Every later left value is at least 3, so it pairs with 1 as well, which is why j never moves back.
array13231ijleftrightcheckpairs1j has passed the whole right half, add 1
pairs for 31right values passed
total1
Every value in the right half pairs with 3, so add 1. That was the last left value of this merge.
array13213merged, sortedcheckpairs1merge the halves into sorted order
range[1, 3]now sorted
Counting is done for this range, so merge the two sorted halves. The parent call needs this range sorted to run the same forward-only sweep one level up. Values moving around inside it is fine: any pair counted later crosses a higher middle, and both of its numbers stay on their own side.
array13213ijleftrightcheck2left value≤2twice 1pairs12 is not more than twice 1 → stop, add 0
pairs for 20right values passed
total1
2 is not more than 2, so 1 and everything after it are too big to pair with 2. No right value is before j, so 2 adds nothing. That was the last left value of this merge.
array13123merged, sortedcheckpairs1merge the halves into sorted order
range[1, 2, 3]now sorted
Counting is done for this range, so merge the two sorted halves. The parent call needs this range sorted to run the same forward-only sweep one level up. Values moving around inside it is fine: any pair counted later crosses a higher middle, and both of its numbers stay on their own side.
array13123ijleftrightcheck1left value≤2twice 1pairs11 is not more than twice 1 → stop, add 0
pairs for 10right values passed
total1
1 is not more than 2, so 1 and everything after it are too big to pair with 1. No right value is before j, so 1 adds nothing. j keeps its place for the next left value.
array13123ijleftrightcheck3left value>2twice 1pairs13 is more than twice 1 → j moves on
left3
right1twice is 2
3 > 2, so 1 forms a pair with 3. j steps past it. Every later left value is at least 3, so it pairs with 1 as well, which is why j never moves back.
array13123ijleftrightcheck3left value≤4twice 2pairs23 is not more than twice 2 → stop, add 1
pairs for 31right values passed
total2
3 is not more than 4, so 2 and everything after it are too big to pair with 3. The 1 right value before j pairs with 3, so add 1. That was the last left value of this merge.
array11233merged, sortedcheckpairs2merge the halves into sorted order
range[1, 1, 2, 3, 3]now sorted
Counting is done for this range, so merge the two sorted halves. The parent call needs this range sorted to run the same forward-only sweep one level up. Values moving around inside it is fine: any pair counted later crosses a higher middle, and both of its numbers stay on their own side.
array11233checkpairs2answer: 2
result2
Every pair crosses the middle of exactly one merge, so each was counted once. The array is now sorted, and 2 is the number of reverse pairs.
05

Common pitfalls

Doubling in 32-bit arithmetic

✗ Wrong
while (j < hi && nums[i] > 2 * nums[j]) j++;
✓ Right
while (j < hi && nums[i] > 2LL * nums[j]) j++;

In C++ and Java, 2 * nums[j] is computed as a 32-bit int. For [2147483647, 1073741824], doubling the second value wraps to −2147483648, so the pair is counted and the answer is 1 instead of 0. Python integers never overflow.

Counting inside the merge comparison

✗ Wrong
if nums[a] > nums[b]:
    count += mid - a
✓ Right
while j < hi and nums[i] > 2 * nums[j]:
    j += 1
count += j - mid

That is the Count Inversions test, left > right, not left > 2 × right. On [3, 2] it counts one pair, but 3 is not more than 4, so the answer is 0.

Halving instead of doubling

✗ Wrong
nums[i] // 2 > nums[j]
✓ Right
nums[i] > 2 * nums[j]

Integer division rounds down and changes the answer for odd values. On [3, 1], 3 // 2 = 1 is not more than 1, so the pair is missed, yet 3 > 2 is true and the answer is 1.

06

Edge cases

Negative numbers

Doubling a negative number makes it smaller, so [-5, -5] has one pair: −5 > −10. The sweep still works, because doubling keeps the right half in sorted order.

07

Complexity

Time
O(n log n)
Space
O(n)
There are about log n levels of merges, and at each level the sweeps and merges together touch every number a constant number of times. The merge buffer holds up to n numbers, and the recursion is only log n deep.
08

Reverse Pairs FAQ

How is Reverse Pairs different from Count Inversions?

Count Inversions counts pairs with nums[i] > nums[j], which is the same comparison the merge already makes, so the count can be added inside the merge loop. Reverse Pairs compares with 2 * nums[j], a different test from the merge's, so it needs its own sweep before each merge.

Can it be solved with a Fenwick tree?

Yes. Read nums left to right, and for each value count how many earlier values are greater than twice it, using a Fenwick tree over the sorted list of all values. Then add the value to the tree. It is also O(n log n), but needs a value-compression step that merge sort avoids.