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 - Merge Sort with Counting INPUT nums = [1, 3, 2, 3, 1] 1 i=0 3 i=1 2 i=2 3 i=3 1 i=4 Reverse Pair Condition: 0 <= i < j < n nums[i] > 2 * nums[j] Valid Pairs Found: (1,4): 3>2*1 (3,4): 3>2*1 nums[1]=3 > 2*nums[4]=2 nums[3]=3 > 2*nums[4]=2 ALGORITHM STEPS 1 Divide Array Split into left and right halves 2 Recursively Sort Sort left and right recursively 3 Count Reverse Pairs Count pairs across halves 4 Merge Halves Merge sorted halves together Merge Sort Tree [1,3,2,3,1] [1,3,2] [3,1] [1,3] [2] [3] [1] Count pairs at each merge step FINAL RESULT Output: 2 Total Reverse Pairs = 2 Identified Reverse Pairs: Pair 1: (i=1, j=4) nums[1]=3 > 2*nums[4]=2 [OK] Pair 2: (i=3, j=4) nums[3]=3 > 2*nums[4]=2 [OK] Complexity Analysis: Time: O(n log n) Space: O(n) Approach: Divide and Conquer Key Insight: Merge Sort naturally compares elements from different halves. During the merge phase, we count pairs where left[i] > 2 * right[j]. Since both halves are sorted, we can use two pointers to efficiently count all valid reverse pairs without checking every combination, reducing time from O(n^2) to O(n log n). TutorialsPoint - Reverse Pairs | Merge Sort with Counting Approach
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