Reverse Pairs (LeetCode 493): Solution and Explanation

Hard
Array
Binary Search
Divide And Conquer
Binary Indexed Tree
Segment Tree
Merge Sort
Ordered Set

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

  1. Write mergeCount(lo, hi) for the half-open range [lo, hi). Ranges of length 0 or 1 return 0.
  2. Split at mid, recurse on both halves, and add their counts.
  3. Set j = mid. For each i in [lo, mid), move j forward while j < hi and nums[i] > 2 * nums[j], then add j - mid.
  4. Merge the two sorted halves into one sorted range.
  5. Return the count. The answer is mergeCount(0, n).

Step-by-step example

nums = [1,3,2,3,1]
  1. The first split is [1,3] and [2,3,1]. Inside [1,3], 1 is not greater than 2 * 3, so no pair.
  2. 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].
  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.
  4. 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))
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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.

Space

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 as 2L * nums[j].
  • Counting inside the merge loop itself. The merge compares nums[i] <= nums[j], which is a different condition from nums[i] > 2 * nums[j], so count in a separate pass first.
  • Resetting j to mid for every i. That makes each merge quadratic; j should 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.