You are given an array of whole numbers, nums. A reverse pair is a pair of positions (i, j) with i < j where the earlier number is more than double the later one: nums[i] > 2 × nums[j].
Return how many reverse pairs the array has.
Example 1
Input: nums = [6, 1, 5, 2] Output: 3 Why: 6 > 2×1, 6 > 2×2 and 5 > 2×2
2 more examples and the constraints
Example 2
Input: nums = [3, 3, 3] Output: 0 Why: 3 is never more than 6
Example 3
Input: nums = [-5, -3] Output: 1 Why: -5 > 2×(-3) = -6
Constraints
- 1 ≤ length of nums ≤ 50,000
- Every number fits in a signed 32-bit integer (−2³¹ to 2³¹ − 1)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every pairO(n²)
- Count during merge sortO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 50,000 numbers | Verdict |
|---|---|---|---|
| Check every pair | O(n²) | Too slow at 50,000 | |
| Count during merge sort | O(n log n) | Best; counts while sorting |
n = how many numbers are in the array.
Edge cases to test
- Overflow. 2 × 2,147,483,647 does not fit in 32 bits. Double in 64-bit (2L, 2LL).
- Negative numbers. [-5, -3] is a pair, because doubling a negative makes it smaller.
- Equal values. [3, 3, 3] has none; positive x is never more than 2x.
- One number. No pairs at all: 0.
- Strictly more. [4, 2] is not a pair: 4 is not more than 4.
Common mistakes
- Computing 2 × nums[j] in 32-bit, which overflows for large values.
- Counting during the merge itself, with the merge test, instead of in a separate walk.
- Resetting j for every i, which turns the count back into O(n²) per merge.
How to talk through it
- 1Clarify. Is it strictly more than double? Can values be negative or near the 32-bit limits?
- 2Give the brute force. Check every pair; say it is O(n²), about a billion checks at 50,000.
- 3Find the structure. Like counting inversions: each pair is split by one merge, where both halves are sorted.
- 4Code the count then the merge. Explain why j only moves forward, and why the doubling is done in 64-bit.
- 5Test out loud. Run a negative pair, equal values and a large value before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?