Reverse Pairs

Hard

Topics
ArrayMerge SortBinary Indexed Tree

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

1031223314
Input:  nums = [1,3,2,3,1]
Output: 2

Example 2

2041325314
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

  1. 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.
  2. Recurse on [lo, mid) and [mid, hi), accumulating their counts.
  3. With both halves sorted, sweep: for each i in the left half, advance j while work[i] > 2 * work[j], then add j - mid — the number of right-half elements that qualify for this i.
  4. Merge the two halves so the level above sees a sorted range.
  5. 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 2

Two 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^4 this 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 reach 2^31 - 1, so the doubling overflows and the comparison silently inverts. Java needs 2L * 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 — resetting j to mid on each i is 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)
Asked at eBay Intuit
SensAI
Beta
Tap the mic to stop voice mode