← Back to index
HardPython4 min read

Reverse Pairs

count pairs where nums[i] > 2 * nums[j] and i < j using merge sort with counting during merge phase.

divide-and-conquermerge-sort

Problem link

View on LeetCode

Solutions in this repo

  • Python../reverse-pairs/solution.pyPython solution

use merge sort but count reverse pairs during merge. for each element in left half, count how many elements in right half satisfy nums[i] > 2 * nums[j]. use two-pointer technique: as left element increases, right pointer can only move forward.

during merge phase, before merging, count pairs: for each left[i], find how many right[j] satisfy left[i] > 2 * right[j]. then merge normally. recursive calls handle subarrays.

counting logic

  • for each left[i], find j where left[i] > 2 * right[j]
  • count = j - (mid + 1) gives number of valid pairs
  • j pointer only moves forward (monotonic)
  • then merge arrays normally

complexity

O(n log n) time from merge sort, counting adds O(n) per level. O(n) space for temporary arrays.