Reverse Pairs (LeetCode 493): Solution and Explanation
Given an integer array, count the index pairs i < j where nums[i] is greater than twice nums[j].
Intuition
Checking every pair is quadratic. Merge sort gives a better structure: every pair (i, j) ends up in different halves at exactly one merge, with i on the left and j on the right.
At that merge both halves are already sorted. Original positions inside a half no longer matter, because every left element came before every right element in the original array.
Walk the sorted left half from small to large with a pointer j into the right half. A bigger left value beats at least as many right values, so j only moves forward and the whole counting pass is linear.
Count first, then merge. Summing the cross counts over all merges counts every reverse pair exactly once.
Approach: Merge sort with a counting pass
- Write
mergeCount(lo, hi)for the half-open range[lo, hi). Ranges of length 0 or 1 return 0. - Split at
mid, recurse on both halves, and add their counts. - Set
j = mid. For eachiin[lo, mid), movejforward whilej < hiandnums[i] > 2 * nums[j], then addj - mid. - Merge the two sorted halves into one sorted range.
- Return the count. The answer is
mergeCount(0, n).
Step-by-step example
nums = [1,3,2,3,1]
- The first split is [1,3] and [2,3,1]. Inside [1,3], 1 is not greater than 2 * 3, so no pair.
- Inside [2,3,1] the split is [2] and [3,1]. [3,1] gives one pair, since 3 > 2 * 1, and sorts to [1,3]. Then [2] against [1,3]: 2 is not greater than 2 * 1, so no pair. The half becomes [1,2,3].
- Top merge: left [1,3], right [1,2,3]. For 1, j stays at the start. For 3, 3 > 2 * 1, so j moves one step and adds 1.
- The counts are 0 + 1 + 0 + 1 = 2, which is the answer.
Code: Python, Java, C++
1class Solution:
2 def reversePairs(self, nums: List[int]) -> int:
3 def merge_count(lo, hi):
4 if hi - lo <= 1:
5 return 0
6 mid = (lo + hi) // 2
7 count = merge_count(lo, mid) + merge_count(mid, hi)
8 j = mid
9 for i in range(lo, mid):
10 while j < hi and nums[i] > 2 * nums[j]:
11 j += 1
12 count += j - mid
13 nums[lo:hi] = sorted(nums[lo:hi])
14 return count
15 return merge_count(0, len(nums))1class Solution {
2 public int reversePairs(int[] nums) {
3 return mergeCount(nums, new int[nums.length], 0, nums.length);
4 }
5
6 private int mergeCount(int[] nums, int[] buf, int lo, int hi) {
7 if (hi - lo <= 1) return 0;
8 int mid = (lo + hi) / 2;
9 int count = mergeCount(nums, buf, lo, mid) + mergeCount(nums, buf, mid, hi);
10 int j = mid;
11 for (int i = lo; i < mid; i++) {
12 while (j < hi && nums[i] > 2L * nums[j]) j++;
13 count += j - mid;
14 }
15 int a = lo, b = mid, t = lo;
16 while (a < mid || b < hi) {
17 if (b >= hi || (a < mid && nums[a] <= nums[b])) buf[t++] = nums[a++];
18 else buf[t++] = nums[b++];
19 }
20 System.arraycopy(buf, lo, nums, lo, hi - lo);
21 return count;
22 }
23}1class Solution {
2public:
3 int reversePairs(vector<int>& nums) {
4 return mergeCount(nums, 0, nums.size());
5 }
6
7 int mergeCount(vector<int>& nums, int lo, int hi) {
8 if (hi - lo <= 1) return 0;
9 int mid = (lo + hi) / 2;
10 int count = mergeCount(nums, lo, mid) + mergeCount(nums, mid, hi);
11 int j = mid;
12 for (int i = lo; i < mid; i++) {
13 while (j < hi && nums[i] > 2LL * nums[j]) j++;
14 count += j - mid;
15 }
16 inplace_merge(nums.begin() + lo, nums.begin() + mid, nums.begin() + hi);
17 return count;
18 }
19};Time and space complexity
O(n log n)
There are log n levels of recursion, and at each level the counting pass and the merge are linear in total.
O(n)
The merge buffer holds n values; the recursion stack adds O(log n).
Other approaches
Binary indexed tree over compressed values (time O(n log n), space O(n))
Scan from right to left. For each value, query how many already-seen values are less than nums[i] / 2, using a Fenwick tree over sorted, compressed values that include every 2 * nums[j]. Then insert nums[i].
Sorted list with binary search (time O(n log n), space O(n))
Keep the values seen so far in a sorted structure and binary search for the count below nums[i] / 2. With a balanced tree this is O(n log n); with a plain array insertion it degrades to O(n^2).
Check every pair (time O(n^2), space O(1))
Two nested loops compare every i < j. Correct but far too slow for 5 * 10^4 elements.
Common mistakes
- Computing
2 * nums[j]in 32-bit arithmetic. With values near 2^31 it overflows; use a 64-bit multiply such as2L * nums[j]. - Counting inside the merge loop itself. The merge compares
nums[i] <= nums[j], which is a different condition fromnums[i] > 2 * nums[j], so count in a separate pass first. - Resetting
jtomidfor everyi. That makes each merge quadratic;jshould only move forward. - Forgetting that negative numbers flip intuition: for -3 and -2, -3 > 2 * -2 = -4 is true, so negatives can form pairs too.
Frequently asked questions
Why is it safe to sort the halves before counting?
Every element of the left half has a smaller original index than every element of the right half. Reordering inside a half does not change which cross pairs satisfy i < j.
Can the count overflow a 32-bit integer?
The largest possible count is n(n-1)/2, about 1.25 * 10^9 for n = 5 * 10^4, which still fits in a signed 32-bit integer.
How is this related to counting inversions?
Inversions count pairs with nums[i] > nums[j]. Reverse pairs only change the condition to nums[i] > 2 * nums[j], so the same merge sort skeleton works with a separate counting pass.