Reverse Pairs solution explained
Reverse Pairs asks how many index pairs i < j satisfy nums[i] > 2 × nums[j]. Use merge sort: after both halves are sorted, walk the left half with a pointer into the right half that only moves forward, counting how many right values are small enough, then merge the halves in a separate pass. The count and the merge need separate passes because the pair condition is not the same as the sort order. The result is O(n log n) time and O(n) extra memory, with a Fenwick tree over compressed values as an equally fast alternative.
By Evin JohnPublished 8 min read
The problem, restated
You get an array of integers, which can be negative. A pair of positions (i, j) with i before j is a reverse pair when the value at i is strictly greater than twice the value at j. Return how many such pairs the array has.
| nums | Count | The pairs |
|---|---|---|
| [5, 2, 1] | 2 | 5 > 4 and 5 > 2; the pair 2, 1 fails because 2 is not more than 2 |
| [3, 1, 6, 2] | 2 | 3 > 2 and 6 > 4 |
| [-1, -1] | 1 | -1 > -2, so equal negative values form a pair |
| [2, 1] | 0 | 2 is not greater than 2 |
| [7] | 0 | A single value has no pair |
The negative case surprises people. Doubling a negative number makes it smaller, so -1 is greater than twice -1, and two equal negatives count. Any solution that assumes reverse pairs need a larger value first is wrong.
What the interviewer is checking
Reverse Pairs is a variation on counting inversions, and most interviewers ask it to see whether you can adapt merge sort rather than recite it. The key insight is that the counting step and the merging step use different comparisons, so they must be separate loops. Interviewers also listen for overflow awareness: in languages with 32-bit integers, 2 × nums[j] can overflow, so the product needs a wider type.
Variations
- Plain inversions (nums[i] > nums[j]). The same code with the factor 1; then counting can happen inside the merge.
- A general factor k. Replace 2 with k; with a non-integer factor, compare a > k × b carefully or cross-multiply.
- Count for each position, not the total. Track original indexes through the sort, as in count-of-smaller problems.
- Pairs within a distance d. Merge sort no longer fits cleanly; a sliding structure over the last d values is needed.
Brute force
def reverse_pairs_slow(nums):
n = len(nums)
return sum(
1 for i in range(n) for j in range(i + 1, n) if nums[i] > 2 * nums[j]
)Merge sort: count, then merge
Split the array, solve each half recursively, and return both halves sorted. Every element of the left half came before every element of the right half in the original array, so cross pairs are exactly pairs (left value a, right value b) with a > 2b. With both halves sorted, as a grows, the set of right values b with 2b < a can only grow. So one pointer r into the right half, never moving backward, counts all cross pairs in one pass. After counting, merge the halves with the ordinary comparison a <= b.
def reverse_pairs(nums):
arr = list(nums)
def sort_count(lo, hi):
if hi - lo <= 1:
return 0
mid = (lo + hi) // 2
pairs = sort_count(lo, mid) + sort_count(mid, hi)
r = mid
for i in range(lo, mid):
while r < hi and arr[i] > 2 * arr[r]:
r += 1
pairs += r - mid
arr[lo:hi] = merge(arr[lo:mid], arr[mid:hi])
return pairs
def merge(left, right):
out, a, b = [], 0, 0
while a < len(left) and b < len(right):
if left[a] <= right[b]:
out.append(left[a])
a += 1
else:
out.append(right[b])
b += 1
return out + left[a:] + right[b:]
return sort_count(0, len(arr))function reversePairs(nums) {
const arr = nums.slice();
const buf = new Array(arr.length);
function sortCount(lo, hi) {
if (hi - lo <= 1) return 0;
const mid = (lo + hi) >> 1;
let pairs = sortCount(lo, mid) + sortCount(mid, hi);
let r = mid;
for (let i = lo; i < mid; i++) {
while (r < hi && arr[i] > 2 * arr[r]) r++;
pairs += r - mid;
}
let a = lo;
let b = mid;
let k = lo;
while (a < mid && b < hi) buf[k++] = arr[a] <= arr[b] ? arr[a++] : arr[b++];
while (a < mid) buf[k++] = arr[a++];
while (b < hi) buf[k++] = arr[b++];
for (let t = lo; t < hi; t++) arr[t] = buf[t];
return pairs;
}
return sortCount(0, arr.length);
}Both versions sort a copy, so the caller's array is left alone. The JavaScript one reuses a single buffer for every merge instead of allocating new arrays, which keeps memory at O(n) and avoids garbage on large inputs.
Trace on [3, 1, 6, 2]
The halves are [3, 1] and [6, 2]. Inside [3, 1], 3 > 2 counts one pair, and the half becomes [1, 3]. Inside [6, 2], 6 > 4 counts one, and it becomes [2, 6]. For the cross pass, the left value 1 is not more than twice 2, and neither is 3, so the pointer never moves and the cross count is 0. Total 2, which matches the table.
Fenwick tree alternative
Scan left to right. For each value x, the earlier values that pair with it are those greater than 2x. Keep a Fenwick tree of counts over the sorted distinct values. The number of earlier values at or below 2x is a prefix query up to the position of 2x in that sorted list, found with bisect_right; subtract it from how many values have been seen. Then add x.
from bisect import bisect_left, bisect_right
def reverse_pairs_bit(nums):
order = sorted(set(nums))
tree = [0] * (len(order) + 1)
found = 0
for seen, x in enumerate(nums):
pos = bisect_right(order, 2 * x)
at_most = 0
while pos > 0:
at_most += tree[pos]
pos -= pos & -pos
found += seen - at_most
slot = bisect_left(order, x) + 1
while slot <= len(order):
tree[slot] += 1
slot += slot & -slot
return foundHere 2x does not need to be one of the stored values: bisect_right counts how many distinct values are at or below it, and that count is the Fenwick position to query. This is the reason to compress the original values only, rather than the values and their doubles together, although compressing both also works.
Complexity
| Approach | Time | Extra memory |
|---|---|---|
| Double loop | O(n²) | O(1) |
| Merge sort with a separate counting pass | O(n log n) | O(n) |
| Fenwick tree over compressed values | O(n log n) | O(n) |
Edge cases
- Equal negative values, which form pairs; equal positive values, which do not.
- Zeros: 0 > 2 × 0 is false, but any positive value before a zero forms a pair.
- Values near the 32-bit limits, where 2 × nums[j] overflows a 32-bit integer.
- A strictly increasing positive array, which has no pairs.
- Empty or single-element arrays, which return 0.
Common mistakes
- Counting inside the merge loop. The merge compares a with b, but pairs need a with 2b: on [3, 2], the merge places 2 ahead of 3, which an inversion-style count records as a pair, yet 3 is not more than 4. That count returns 1 instead of 0.
- Rewriting the test as a // 2 > b with integer division. On [3, 1], 3 > 2 is a pair, but 3 // 2 is 1, which is not more than 1, so the pair is lost.
- Multiplying in 32-bit arithmetic in C++ or Java. Cast to a 64-bit type first.
- Resetting the right pointer for every left element, which turns the cross pass back into O(n²).
- Assuming pairs need a positive earlier value, which misses pairs like (-1, -1).
How to explain it out loud
Fictional example
- Candidate
- This looks like counting inversions, but with a factor of two. In merge sort, every left element is earlier than every right element, so cross pairs are left values more than twice a right value.
- Candidate
- With both halves sorted, I can count those with one pointer into the right half that only moves forward. Then I merge with the normal comparison. Those have to be separate loops, because the order I merge in is not the order the pair condition needs.
- Interviewer
- Anything to watch with large numbers?
- Candidate
- Two times a 32-bit value can overflow, so in Java or C++ I would use a long for the product. In Python it does not matter.
Related problems
Count of Range Sum runs the same count-then-merge recursion on prefix sums with a two-sided window. Count of Smaller Numbers After Self counts per position and shows the Fenwick approach scanned from the right. Process Tasks Using Servers is a change of pace with heaps, and Interval List Intersections is another problem where a pointer that only moves forward does the work of a nested loop.
Practicing with Natively
The sentence that earns credit here is why counting and merging must be separate. Say it in a mock round on Mac or Windows with Natively transcribing, and check afterwards that it came out before the code. After you have tried the problem on your own, Natively can read it from a screenshot and suggest an approach to compare, which is a quick way to see the Fenwick version beside your merge sort. Read about the AI interview assistant.
Questions people ask
How do you solve Reverse Pairs?
Use merge sort. After both halves are sorted, move a pointer through the right half while the current left value is more than twice the right value, add how far it has moved, and merge in a separate pass.
Why can't the counting happen inside the merge?
The merge orders values by a <= b, but a reverse pair needs a > 2b. Those comparisons disagree, so counting during the merge counts plain inversions instead.
What is the time complexity of Reverse Pairs?
O(n log n) time and O(n) extra memory with merge sort or a Fenwick tree. The double loop is O(n squared).
Do negative numbers change anything?
Yes. Doubling a negative makes it smaller, so equal negatives such as -1 and -1 form a pair. Compare with exact integers and use 64-bit math in typed languages.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
