Problem Description
Given an integer array nums, count the number of reverse pairs in the array. A reverse pair is defined as a pair (i, j) where 0 <= i < j < nums.length and nums[i] > 2 * nums[j].
Key Insights
- The brute force solution checks every possible pair, resulting in O(n^2) time complexity, which is too slow for the given constraints.
- A modified merge sort can be used to both sort the array and count reverse pairs efficiently.
- During the merge process, since the two halves are sorted, a two-pointer technique can efficiently count how many numbers in the right half satisfy the reverse pair condition for each number in the left half.
- Alternative approaches include Binary Indexed Trees or Segment Trees, but merge sort provides a clean divide and conquer solution.
Space and Time Complexity
Time Complexity: O(n log n) – Each level of the merge sort takes O(n) time and there are O(log n) levels. Space Complexity: O(n) – Additional space is required for the temporary array during merging.
Solution
We solve the problem using a modified merge sort. The idea is to recursively split the array into halves, count reverse pairs in each half, and then count reverse pairs across the two halves before merging them. When merging two sorted halves, a two-pointer approach can be used to count the reverse pairs quickly. After counting, the two halves are merged in sorted order.