Reverse Pairs - Problem
Reverse Pairs is a challenging array problem that tests your ability to count special inversions efficiently.
Given an integer array
For example, in the array
Your task: Return the total count of such reverse pairs.
Given an integer array
nums, you need to find the number of reverse pairs in the array. A reverse pair is defined as a pair of indices (i, j) where:0 โค i < j < nums.length(i comes before j)nums[i] > 2 * nums[j](the first element is more than twice the second)
For example, in the array
[1, 3, 2, 3, 1], we have reverse pairs at indices (1,4) because 3 > 2*1 = 2 and (3,4) because 3 > 2*1 = 2.Your task: Return the total count of such reverse pairs.
Input & Output
example_1.py โ Basic Case
$
Input:
[1, 3, 2, 3, 1]
โบ
Output:
2
๐ก Note:
The reverse pairs are (1,4) and (3,4). At index 1, nums[1]=3 and nums[4]=1, so 3 > 2*1 = 2. At index 3, nums[3]=3 and nums[4]=1, so 3 > 2*1 = 2.
example_2.py โ No Pairs
$
Input:
[2, 4, 3, 5, 1]
โบ
Output:
3
๐ก Note:
The reverse pairs are (1,4), (2,4), and (3,4). nums[1]=4 > 2*1=2, nums[2]=3 > 2*1=2, and nums[3]=5 > 2*1=2.
example_3.py โ Single Element
$
Input:
[1]
โบ
Output:
0
๐ก Note:
With only one element, there are no pairs possible, so the answer is 0.
Constraints
- 1 โค nums.length โค 5 ร 104
- -231 โค nums[i] โค 231 - 1
- Watch out for integer overflow when computing 2 * nums[j]
Visualization
Tap to expand
Understanding the Visualization
1
Divide Phase
Split the array recursively into smaller subarrays, like creating tournament brackets
2
Conquer Phase
Process the smallest subarrays first and work your way up
3
Count Cross-pairs
When merging two sorted halves, count pairs where left element > 2 * right element
4
Merge Phase
Combine the sorted halves while maintaining the total count
Key Takeaway
๐ฏ Key Insight: By using merge sort's divide-and-conquer structure, we can count reverse pairs efficiently in O(n log n) time, much better than the O(nยฒ) brute force approach.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code