#493

Reverse Pairs

Hard Merge sort counting

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Count pairs (i, j) with i < j and nums[i] > 2 × nums[j].

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: count pairs i < j with nums[i] > 2 × nums[j].

Why this works: inside merge sort both halves are sorted, so one pointer sweep counts pairs across the halves before merging.

Example: [1, 3, 2, 3, 1]

pairs: (3, 1) at indexes 1, 4 and (3, 1) at 3, 4answer 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Computing 2 * nums[j] in int — values up to 2^31 overflow.

Solve on LeetCode ↗
Complexity
  • Time: O(n log n).
  • Space: O(n).
Topic: Sorting
🎬 Episodes 24–28: video coming soon