Reverse Pairs - Problem
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.lengthandnums[i] > 2 * nums[j]
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,3,2,3,1]
›
Output:
2
💡 Note:
The reverse pairs are (1,4) where nums[1]=3 > 2*nums[4]=2*1=2, and (3,4) where nums[3]=3 > 2*nums[4]=2*1=2
Example 2 — No Pairs
$
Input:
nums = [2,4,3,5,1]
›
Output:
3
💡 Note:
Pairs: (0,4) since 2>2*1=2 is false, (1,4) since 4>2*1=2 is true, (2,4) since 3>2*1=2 is true, (3,4) since 5>2*1=2 is true
Example 3 — Minimum Size
$
Input:
nums = [5,1]
›
Output:
1
💡 Note:
Only one pair (0,1): 5 > 2*1 = 2, so count = 1
Constraints
- 1 ≤ nums.length ≤ 5 × 104
- -231 ≤ nums[i] ≤ 231 - 1
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [1,3,2,3,1] - find reverse pairs
2
Check
For each i < j, check if nums[i] > 2 * nums[j]
3
Count
Return total count of valid pairs
Key Takeaway
🎯 Key Insight: Use merge sort to count reverse pairs efficiently in O(n log n) time
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code