Reverse Pairs

HardDivide & Conquer · Merge Sort🧩 Recursion & Divide and ConquerLeetCode #493 ↗Updated

Problem

Given an integer array nums, count the index pairs (i, j) with i < j where the earlier element is more than twice the later one, i.e. nums[i] > 2 · nums[j]. Values span the full int range, so the doubled value must not overflow.
Input[1,3,2,3,1]Output2 (3 > 2·1 twice)
Input[5,4,3,2,1]Output4
Input[-5,-5]Output1 (-5 > -10)

1 ≤ n ≤ 5·104  ·  -231 ≤ nums[i] ≤ 231-1

Try it yourself

Java
class Solution {
    public int reversePairs(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
During merge sort, the left and right halves are each sorted and every left index is still before every right index. So the pairs that cross the midpoint can be counted with one forward-only pointer before merging — O(n) per level.
PatternRecursion & Divide and Conquer

Instinct If the answer for n items can be built from the same problem on halves (or smaller pieces) plus a cheap combine step - split, recurse, merge.

Memory hack Split it, trust it, stitch it - nail the base case, take the leap of faith on smaller calls, then glue their answers together.

Open the Recursion & Divide and Conquer guide →

Approaches

Brute ForceCheck Every Pair

Time O(n²)Space O(1)

Two nested loops test nums[i] > 2L * nums[j] for every i < j. Doing the doubling in long keeps values like 231-1 from wrapping negative.

Java
public int reversePairs(int[] nums) {
    int count = 0;
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[i] > 2L * nums[j]) count++; // 2L: no int overflow
        }
    }
    return count;
}

Obviously correct; ~1.25·109 checks at n = 5·104 is too slow.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every PairO(n²)O(1)
BetterFenwick Tree over Ranked ValuesO(n log n)O(n)
OptimalMerge Sort with Cross-CountO(n log n)O(n)
Common pitfalls
  • Computing 2 * nums[j] in int — overflows for |values| > 230.
  • Counting inside the merge comparison — the merge order and the 2x condition disagree.
  • Resetting j for every i — turns the cross-count back into O(n²).
Interview tips
  • Link it to “count inversions”: same merge-sort skeleton, different cross condition.
  • Explain why left-before-right is preserved when both halves are sorted independently.
  • Mention the BIT alternative as a follow-up if the interviewer wants an online version.
Pattern
Merge sort with cross-half counting → count pairs i < j satisfying a monotone comparison between their values.
My notes saved in this browser