Reverse Pairs is a challenging array problem that tests your ability to count special inversions efficiently.

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
Reverse Pairs: Divide and Conquer Strategy[1,3,2,3,1][1,3,2][3,1]Sort: [1,2,3]Sort: [1,3]Count Cross Pairs3 > 2ร—1 โœ“ (1 pair found)Final: [1,1,2,3,3]
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
58.0K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen