#493

Reverse Pairs

Hard
ArrayBinary SearchDivide and ConquerBinary Indexed TreeSegment TreeMerge SortOrdered SetDivide and ConquerMerge Sort
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

Using a modified merge sort allows us to count reverse pairs efficiently during the sorting process. This takes advantage of the divide-and-conquer strategy to reduce the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Define a recursive function that sorts the array and counts reverse pairs.
  2. 2Step 2: Split the array into two halves and recursively sort each half.
  3. 3Step 3: While merging the two halves, count how many elements in the left half are greater than twice the elements in the right half.
  4. 4Step 4: Merge the two halves back together in sorted order.
solution.py40 lines
1def merge_and_count(nums, temp, left, mid, right):
2    count = 0
3    j = mid + 1
4    for i in range(left, mid + 1):
5        while j <= right and nums[i] > 2 * nums[j]:
6            j += 1
7        count += (j - (mid + 1))
8    i, j, k = left, mid + 1, left
9    while i <= mid and j <= right:
10        if nums[i] <= nums[j]:
11            temp[k] = nums[i]
12            i += 1
13        else:
14            temp[k] = nums[j]
15            j += 1
16        k += 1
17    while i <= mid:
18        temp[k] = nums[i]
19        i += 1
20        k += 1
21    while j <= right:
22        temp[k] = nums[j]
23        j += 1
24        k += 1
25    for i in range(left, right + 1):
26        nums[i] = temp[i]
27    return count
28
29def reversePairs(nums):
30    temp = [0] * len(nums)
31    return merge_sort_and_count(nums, temp, 0, len(nums) - 1)
32
33def merge_sort_and_count(nums, temp, left, right):
34    count = 0
35    if left < right:
36        mid = (left + right) // 2
37        count += merge_sort_and_count(nums, temp, left, mid)
38        count += merge_sort_and_count(nums, temp, mid + 1, right)
39        count += merge_and_count(nums, temp, left, mid, right)
40    return count

Complexity note: The time complexity is O(n log n) due to the merge sort process, which divides the array and merges it back while counting reverse pairs. The space complexity is O(n) because we need an additional array for merging.

  • 1Understanding how to count pairs efficiently during sorting is crucial.
  • 2Recognizing the need for a divide-and-conquer strategy can significantly reduce time complexity.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.