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]

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
Reverse Pairs: Find (i,j) where nums[i] > 2 * nums[j] and i < jInput: [1, 3, 2, 3, 1]13231i=0i=1i=2i=3j=4Pair (1,4): 3 > 2*1 = 2 ✓Pair (3,4): 3 > 2*1 = 2 ✓Output: 2 reverse pairs foundCondition: i < j AND nums[i] > 2 * nums[j]
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
Asked in
Google 25 Microsoft 18 Amazon 15 Facebook 12
180.0K Views
Medium Frequency
~35 min Avg. Time
4.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