Reverse Pairs
Hard
Topics
Given an integer array nums, return the number of reverse pairs. A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
Example 1
Input: nums = [1,3,2,3,1] Output: 2
Example 2
Input: nums = [2,4,3,5,1] Output: 3
Constraints
- 1 <= nums.length <= 5*10^4
- -2^31 <= nums[i] <= 2^31 - 1
Editorial — intuition, approach, complexity and pitfalls
Intuition
The definition is a double loop, so the brute force writes itself: for every i < j, test nums[i] > 2 * nums[j]. That is O(n^2), and with n up to 5*10^4 it is about 1.25 billion comparisons — too slow, and the reason this problem is Hard rather than Easy.
To do better, notice what the brute force wastes. It compares nums[i] against each later element one at a time, when what it really wants is a count: how many later elements are small enough. If the later elements were sorted, that count would be one binary search instead of a scan.
And here is the part that makes it work: sorting a suffix does not change the answer. The condition only cares which side of j an element is on, never the order within that side. So we are free to sort as we go, as long as we count each cross pair before the two sides are mixed together.
That is exactly the shape of merge sort. Split the array; recursively solve both halves; then, with both halves sorted, count the pairs that straddle the split. Every pair (i, j) is straddling at exactly one level of the recursion — the level where i and j first land in different halves — so each is counted once and none is missed.
The straddling count itself is linear, not logarithmic, because of a monotonicity argument. Walk i forward through the left half, which is sorted ascending. As nums[i] grows, the set of right-half elements satisfying nums[i] > 2 * nums[j] can only grow. So j advances and never retreats, and the whole sweep is O(left + right).
Approach
- Copy the input into a working array, so the caller's array is not reordered, and allocate one merge buffer up front rather than one per recursive call.
- Recurse on
[lo, mid)and[mid, hi), accumulating their counts. - With both halves sorted, sweep: for each
iin the left half, advancejwhilework[i] > 2 * work[j], then addj - mid— the number of right-half elements that qualify for thisi. - Merge the two halves so the level above sees a sorted range.
- Return the total.
The order of steps 3 and 4 is not interchangeable. Count first, merge second: once merged, the information about which side an element came from is gone.
Dry Run
nums = [1, 3, 2, 3, 1], expected answer 2. The qualifying pairs are (3, 1) at indices (1,4) and (3,4) — both because 3 > 2*1.
split to [1,3] | [2,3,1]
merge [1] with [3] 1 > 2*3? no -> 0 pairs
left half sorted [1,3]
merge [3] with [1] 3 > 2*1? YES -> 1 pair
sorted [1,3]
merge [2] with [1,3] 2 > 2*1? no -> 0 pairs
right half sorted [1,2,3] running total 1
merge [1,3] with [1,2,3] 1 > 2*anything? no -> 0
3 > 2*1 = 2? YES, and
3 > 2*2 = 4? no -> 1 pair
fully sorted [1,1,2,3,3] total 2Two things the trace shows. The pair at indices (3,4) is counted deep in the recursion, while the pair at (1,4) is only counted at the top level — because that is where indices 1 and 4 first fall on opposite sides of a split. And at the final merge, j stopped after one step for the value 3 and never moved again, which is the monotonicity that keeps the sweep linear.
Complexity
- Time — O(n log n): merge sort's log n levels, with O(n) work per level for the counting sweep and O(n) for the merge. At
n = 5*10^4this runs in a fraction of a second, against roughly 1.25 billion comparisons for the O(n^2) brute force. - Space — O(n): the working copy and one shared merge buffer, plus O(log n) of recursion stack. Allocating a fresh buffer inside each recursive call still gives O(n) peak but churns through O(n log n) total allocation, which is worth avoiding.
Common Pitfalls
- Merging before counting. After the merge the two sides are indistinguishable and the cross pairs are unrecoverable.
- Computing
2 * nums[j]in 32-bit arithmetic. Values reach2^31 - 1, so the doubling overflows and the comparison silently inverts. Java needs2L *and C++2LL *; Python is arbitrary precision and JavaScript's doubles are exact this far, so only two of the four languages need the widening. - Binary searching the right half for each
i. It is correct and gives O(n log^2 n), but the two-pointer sweep is linear for free because the left half is already sorted — resettingjtomidon eachiis the mistake that throws that away. - Counting with
>=instead of>. The condition is strict, so[2, 1]gives one pair but[2, 1]under>=would also admit equality cases that do not qualify. - Sorting the whole array first "to help". That destroys the index order the problem is defined on, and the answer becomes 0 for every input.
- Accumulating the count in a 32-bit int. The maximum is
n(n-1)/2, about 1.25*10^9 at the constraint limit, which fits in a signed 32-bit int but leaves little room; accumulating in 64-bit and narrowing at the end is the safer habit.
Full Solution — all languages
class Solution:
def reversePairs(self, nums):
n = len(nums)
if n < 2:
return 0
work = list(nums) # sorted in place as we go; the input is left alone
buf = [0] * n # one shared merge buffer, not one per call
def count_and_sort(lo, hi):
if hi - lo <= 1:
return 0
mid = (lo + hi) // 2
total = count_and_sort(lo, mid) + count_and_sort(mid, hi)
# Both halves are sorted now, so cross pairs can be counted in one
# linear sweep: as work[i] grows, the set of qualifying j only grows,
# which means j never has to move backwards.
j = mid
for i in range(lo, mid):
while j < hi and work[i] > 2 * work[j]:
j += 1
total += j - mid
# standard merge, so the half is sorted for the level above
i, j, k = lo, mid, lo
while i < mid and j < hi:
if work[i] <= work[j]:
buf[k] = work[i]; i += 1
else:
buf[k] = work[j]; j += 1
k += 1
while i < mid:
buf[k] = work[i]; i += 1; k += 1
while j < hi:
buf[k] = work[j]; j += 1; k += 1
work[lo:hi] = buf[lo:hi]
return total
return count_and_sort(0, n)import java.util.*;
class Solution {
private int[] work, buf;
public int reversePairs(int[] nums) {
int n = nums.length;
if (n < 2) return 0;
work = nums.clone(); // sorted as we go; the caller's array is left alone
buf = new int[n]; // one shared merge buffer
return (int) countAndSort(0, n);
}
private long countAndSort(int lo, int hi) {
if (hi - lo <= 1) return 0;
int mid = lo + (hi - lo) / 2;
long total = countAndSort(lo, mid) + countAndSort(mid, hi);
// Both halves are sorted, so one linear sweep counts the cross pairs:
// as work[i] grows the qualifying set only grows, so j never retreats.
// 2L, not 2 -- values reach 2^31-1 and 2 * nums[j] would overflow an int.
int j = mid;
for (int i = lo; i < mid; i++) {
while (j < hi && (long) work[i] > 2L * work[j]) j++;
total += j - mid;
}
int a = lo, b = mid, k = lo;
while (a < mid && b < hi) buf[k++] = work[a] <= work[b] ? work[a++] : work[b++];
while (a < mid) buf[k++] = work[a++];
while (b < hi) buf[k++] = work[b++];
System.arraycopy(buf, lo, work, lo, hi - lo);
return total;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
vector<int> work, buf;
long long countAndSort(int lo, int hi) {
if (hi - lo <= 1) return 0;
int mid = lo + (hi - lo) / 2;
long long total = countAndSort(lo, mid) + countAndSort(mid, hi);
// Both halves are sorted, so one linear sweep counts the cross pairs:
// as work[i] grows the qualifying set only grows, so j never retreats.
// 2LL, not 2 -- values reach 2^31-1 and 2 * work[j] would overflow an int.
int j = mid;
for (int i = lo; i < mid; i++) {
while (j < hi && (long long) work[i] > 2LL * work[j]) j++;
total += j - mid;
}
int a = lo, b = mid, k = lo;
while (a < mid && b < hi) buf[k++] = work[a] <= work[b] ? work[a++] : work[b++];
while (a < mid) buf[k++] = work[a++];
while (b < hi) buf[k++] = work[b++];
copy(buf.begin() + lo, buf.begin() + hi, work.begin() + lo);
return total;
}
public:
int reversePairs(vector<int>& nums) {
int n = nums.size();
if (n < 2) return 0;
work = nums; // sorted as we go; the caller's vector is untouched
buf.assign(n, 0); // one shared merge buffer
return (int) countAndSort(0, n);
}
};/**
* @param {number[]} nums
* @return {number}
*/
var reversePairs = function (nums) {
const n = nums.length;
if (n < 2) return 0;
const work = nums.slice(); // sorted as we go; the caller's array is left alone
const buf = new Array(n); // one shared merge buffer
// JS numbers are doubles, so 2 * work[j] is exact well past 2^31 and needs no
// widening -- unlike the Java and C++ versions.
const countAndSort = (lo, hi) => {
if (hi - lo <= 1) return 0;
const mid = lo + ((hi - lo) >> 1);
let total = countAndSort(lo, mid) + countAndSort(mid, hi);
// Both halves are sorted, so one linear sweep counts the cross pairs:
// as work[i] grows the qualifying set only grows, so j never retreats.
let j = mid;
for (let i = lo; i < mid; i++) {
while (j < hi && work[i] > 2 * work[j]) j++;
total += j - mid;
}
let a = lo, b = mid, k = lo;
while (a < mid && b < hi) buf[k++] = work[a] <= work[b] ? work[a++] : work[b++];
while (a < mid) buf[k++] = work[a++];
while (b < hi) buf[k++] = work[b++];
for (let t = lo; t < hi; t++) work[t] = buf[t];
return total;
};
return countAndSort(0, n);
};