AlgoInsight

DSA problem

Reverse Pairs

HardMerge SortPattern: Merge Sorttop300AmazonGoogleMicrosoftMetaBloombergApple

Given an integer array nums, return the number of important reverse pairs. A reverse pair is a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].

The brute-force approach checks every pair, costing O(n²) time, which is far too slow for the upper input bounds. The challenge is to count these pairs in O(n log n), which strongly hints at a divide-and-conquer technique built on top of a sorting algorithm — specifically, modified merge sort.

The key observation is that merge sort gives us, at every level, two halves that have just been sorted. Before merging, we can count the reverse pairs that span across the halves (where i is in the left half and j is in the right half) by sweeping two pointers: for each i in [lo..mid], advance a pointer j in [mid + 1..hi] while nums[i] > 2 * nums[j]. Because both halves are sorted, this sweep is total-linear across all i. The number of valid j positions for each i is added to a running count.

After counting, we perform the standard merge step to produce a sorted range. Recursion handles the within-half pairs at deeper levels. To prevent integer overflow when computing 2 * nums[j] — values can reach 2 * 10⁹ — we cast to a 64-bit integer (long in Java / C++, native int is fine in Python, number is safe in JS up to 2⁵³). Overall: O(n log n) time, O(n) space for the merge buffer.

Examples

Example 1
Input: nums = [1,3,2,3,1]
Output: 2
Explanation: The reverse pairs are (i=1, j=4) since 3 > 2*1, and (i=3, j=4) since 3 > 2*1. That is exactly 2 important reverse pairs.
Example 2
Input: nums = [2,4,3,5,1]
Output: 3
Explanation: The important reverse pairs are (1,4): 4 > 2*1, (2,4): 3 > 2*1, and (3,4): 5 > 2*1. Three pairs in total.
Example 3
Input: nums = [5,4,3,2,1]
Output: 4
Explanation: Pairs counted: (5,2)→5>4, (5,1)→5>2, (4,1)→4>2, (3,1)→3>2. The other ordered pairs do not satisfy nums[i] > 2*nums[j].

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

merge-sortdivide-and-conquerarraybinary-indexed-tree

Browse all DSA problems