Reverse Pairs Problem
Description
LeetCode Problem 493.
Given an integer array nums, return the number of reverse pairs in the array.
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
Solution
Approach: Merge Sort with a Counting Pass
Checking every pair takes O(n2) time, too slow for 5 · 104 numbers. Merge sort lets us count pairs in bulk.
Write sortAndCount(lo, hi), which sorts nums[lo..hi] and returns the number of reverse pairs inside it. Split the range at mid. Every pair (i, j) is either entirely in the left half, entirely in the right half, or has i on the left and j on the right. The first two kinds are counted by the recursive calls. For the third kind, the order within each half no longer matters (every left index is still before every right index), so we can count them after both halves are sorted:
- Keep a pointer
jinto the right half, starting atmid + 1. - For each
iin the left half, in increasing order ofnums[i], movejforward whilenums[i] > 2 * nums[j]. All right-half values beforejform a pair withi, so addj - (mid + 1). - Since
nums[i]only grows,jnever has to move back, so this pass is linear. - Merge the two sorted halves as usual.
Count in a separate pass before merging. The condition nums[i] > 2 * nums[j] is not the same comparison the merge uses, so the two cannot be done in one loop.
The detail people get wrong: 2 * nums[j] overflows a 32-bit integer when nums[j] is near ±231. Do the comparison in 64-bit (long / long long). With nums = [-2147483648, -2147483648] the answer is 1, and the overflowing version gets it wrong.
Complexity: O(n log n) time and O(n) space for the merge buffer, where n is the length of nums.
class Solution:
def reversePairs(self, nums: List[int]) -> int:
self.buffer = [0] * len(nums)
return self.sort_and_count(nums, 0, len(nums) - 1)
def sort_and_count(self, nums: List[int], lo: int, hi: int) -> int:
"""Sort nums[lo..hi] and return the number of reverse pairs inside it."""
if lo >= hi:
return 0
mid = (lo + hi) // 2
count = self.sort_and_count(nums, lo, mid) + self.sort_and_count(nums, mid + 1, hi)
# Both halves are sorted. For each i on the left, j moves past every right value with nums[i] > 2 * nums[j];
# a larger nums[i] can only move j further, so j never goes back.
j = mid + 1
for i in range(lo, mid + 1):
while j <= hi and nums[i] > 2 * nums[j]:
j += 1
count += j - (mid + 1)
# Merge the two sorted halves.
left, right, k = lo, mid + 1, lo
while left <= mid or right <= hi:
if right > hi or (left <= mid and nums[left] <= nums[right]):
self.buffer[k] = nums[left]
left += 1
else:
self.buffer[k] = nums[right]
right += 1
k += 1
nums[lo:hi + 1] = self.buffer[lo:hi + 1]
return count
Now write it from memory
Close the write-up and solve it yourself against the tests.