Reverse Pairs
LeetCode 493 · Hard · solution, intuition & step-by-step walkthrough
Merge sort; count cross pairs before each merge.
This is how I solved Reverse Pairs (LeetCode 493), a hard problem from the Advanced / Mixed pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Like counting inversions with merge sort. Before merging two sorted halves, count pairs with left[i] > 2·right[j] using two pointers — because both halves are sorted, once left[i] qualifies, every later left element does too.
Approach
- 1
Split recursively and sort each half.
- 2
Two pointers: if left[i] > 2·right[j], add len(left) − i and advance j; else advance i.
- 3
Then merge normally.
How I solved it
Merge sort countingPythonO(n log n) time
class Solution:
def merge(self, left, right, obj):
result = []
l = r = 0
i = j = 0
while i < len(left) and j < len(right):
if left[i] > 2 * right[j]:
obj["count"] += len(left) - i
j += 1
else:
i += 1
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l]); l += 1
else:
result.append(right[r]); r += 1
return result + left[l:] + right[r:]
def mergeSort(self, arr, obj):
length = len(arr)
if length < 2:
return arr
midPoint = length // 2
left = arr[:midPoint]
right = arr[midPoint:]
return self.merge(self.mergeSort(left, obj), self.mergeSort(right, obj), obj)
def reversePairs(self, arr):
obj = {"count": 0}
self.mergeSort(arr, obj)
return obj["count"]Reverse Pairs — FAQ
What is the intuition behind Reverse Pairs?
Like counting inversions with merge sort. Before merging two sorted halves, count pairs with left[i] > 2·right[j] using two pointers — because both halves are sorted, once left[i] qualifies, every later left element does too.
How do you solve Reverse Pairs (LeetCode 493)?
1. Split recursively and sort each half. 2. Two pointers: if left[i] > 2·right[j], add len(left) − i and advance j; else advance i. 3. Then merge normally.
What is the time and space complexity of Reverse Pairs?
Time: O(n log n). Space: O(n). (Accepted approach: Merge sort counting.)
What are common mistakes in Reverse Pairs?
Count before merging — the halves must still be separate.