Reverse Pairs

Pattern: Basic sorts

hard

Count pairs i < j with nums[i] > 2 × nums[j] in O(n log n). Count across the two sorted halves with a pointer that only moves forward, then merge.

The problem

You are given an array nums of between 1 and 50,000 whole numbers, each anywhere in the 32-bit range. A reverse pair is a pair of positions i < j with nums[i] > 2 × nums[j]. Return how many there are. For example, [1, 3, 2, 3, 1] has 2: both 3s are more than twice the final 1.

The function name reversePairs matches LeetCode. Use the link above for the exact statement.

Think first

  • How is this like counting inversions? What is different about the condition?
  • If both halves are sorted, and nums[left] > 2 × nums[right] holds, what can you say about bigger left values?
  • What happens when you compute 2 × nums[j] for a value near 2³¹ in a 32-bit int?

Hints

    Brute force, and why it fails

    Check every pair i < j: about n²/2, or 1.25 billion comparisons for 50,000 numbers. That is too slow. The merge sort approach does it in O(n log n).

    The key insight

    Sorting each half does not change which pairs cross between the halves, only their order. Once both halves are sorted, one forward-only pointer counts all the crossing pairs in a single pass.

    Dry run

    10 
    31 
    22 
    33 
    14 
    count0

    nums = [1, 3, 2, 3, 1]. Merge sort splits it into [1, 3, 2] and [3, 1], and counts inside each part first.

    Step 1 of 6

    The plan

    function sortAndCount(nums, low, high):
        if low >= high:
            return 0
        mid = low + (high - low) div 2
        count = sortAndCount(nums, low, mid) + sortAndCount(nums, mid + 1, high)
        right = mid + 1
        for left from low to mid:                   # both halves are sorted now
            while right <= high and nums[left] > 2 * nums[right]:   # 64-bit multiply
                right = right + 1
            count = count + (right - (mid + 1))
        merge nums[low..mid] and nums[mid+1..high]
        return count
    

    The Python version does the final merge with sorted on the range. Python's sort spots the two sorted runs and merges them in linear time.

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    At each level, the counting pass moves left and right across the range once, and the merge is linear. The merge needs O(n) temporary space.

    Edge cases

    • One element: 0 pairs.
    • Negative values need care, because doubling a negative makes it smaller. -5 is more than 2 × (-5) = -10, so [-5, -5] has one pair.
    • Values near the limits: 2 × 2147483647 and 2 × -2147483648 need 64 bits.
    • Reversed input such as [5, 4, 3, 2, 1]: only pairs where the first is more than double the second count.
    I've built my logic, show the code

    Java

    class Solution {
        public int reversePairs(int[] nums) {
            return sortAndCount(nums, 0, nums.length - 1);
        }
    
        private int sortAndCount(int[] nums, int low, int high) {
            if (low >= high) {
                return 0;
            }
            int mid = low + (high - low) / 2;
            int count = sortAndCount(nums, low, mid) + sortAndCount(nums, mid + 1, high);
            int right = mid + 1;
            for (int left = low; left <= mid; left++) {           // both halves are sorted here
                while (right <= high && (long) nums[left] > 2L * nums[right]) {
                    right++;
                }
                count += right - (mid + 1);                       // pairs for this nums[left]
            }
            int[] merged = new int[high - low + 1];
            int a = low;
            int b = mid + 1;
            int k = 0;
            while (a <= mid && b <= high) {
                merged[k++] = nums[a] <= nums[b] ? nums[a++] : nums[b++];
            }
            while (a <= mid) {
                merged[k++] = nums[a++];
            }
            while (b <= high) {
                merged[k++] = nums[b++];
            }
            for (int i = 0; i < merged.length; i++) {
                nums[low + i] = merged[i];
            }
            return count;
        }
    }

    C++

    class Solution {
    public:
        int reversePairs(vector<int>& nums) {
            return sortAndCount(nums, 0, static_cast<int>(nums.size()) - 1);
        }
    
        int sortAndCount(vector<int>& nums, int low, int high) {
            if (low >= high) {
                return 0;
            }
            int mid = low + (high - low) / 2;
            int count = sortAndCount(nums, low, mid) + sortAndCount(nums, mid + 1, high);
            int right = mid + 1;
            for (int left = low; left <= mid; left++) {           // both halves are sorted here
                while (right <= high && static_cast<long long>(nums[left]) > 2LL * nums[right]) {
                    right++;
                }
                count += right - (mid + 1);                       // pairs for this nums[left]
            }
            vector<int> merged;
            merged.reserve(high - low + 1);
            int a = low;
            int b = mid + 1;
            while (a <= mid && b <= high) {
                merged.push_back(nums[a] <= nums[b] ? nums[a++] : nums[b++]);
            }
            while (a <= mid) {
                merged.push_back(nums[a++]);
            }
            while (b <= high) {
                merged.push_back(nums[b++]);
            }
            for (int i = 0; i < static_cast<int>(merged.size()); i++) {
                nums[low + i] = merged[i];
            }
            return count;
        }
    };

    Python

    class Solution:
        def reversePairs(self, nums: list[int]) -> int:
            return self.sortAndCount(nums, 0, len(nums) - 1)
    
        def sortAndCount(self, nums, low, high):
            if low >= high:
                return 0
            mid = (low + high) // 2
            count = self.sortAndCount(nums, low, mid) + self.sortAndCount(nums, mid + 1, high)
            right = mid + 1
            for left in range(low, mid + 1):                      # both halves are sorted here
                while right <= high and nums[left] > 2 * nums[right]:
                    right += 1
                count += right - (mid + 1)                        # pairs for this nums[left]
            nums[low:high + 1] = sorted(nums[low:high + 1])       # merge (Python's sort merges two sorted runs in O(n))
            return count

    Common mistakes

    • Doubling in 32 bits, which overflows and gives wrong comparisons.
    • Counting during the merge with the merge's comparison. The condition is different, so it needs its own pass.
    • Resetting right for every left, which makes the counting pass O(n²).

    Similar problems