AlgoMaster Logo

Reverse Pairs

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The problem asks us to count the number of important reverse pairs (i, j) such that i < j and nums[i] > 2 * nums[j]. A straightforward approach is to evaluate every possible pair (i, j) and check the condition. This leads to a simple double loop solution.

Steps:

  1. Iterate over each pair (i, j) where i < j.
  2. For each pair, check if nums[i] > 2 * nums[j].
  3. Count all such pairs.

Code:

2. Merge Sort with Modification

Intuition:

The brute-force solution is inefficient for large inputs. By using a modified version of merge sort, we can efficiently count reverse pairs. The essential insight is to leverage the sorted order of the array to count pairs more efficiently.

Steps:

  1. Use merge sort to sort the array.
  2. During the merge process, for each left element, count how many elements in the right sorted array satisfy the reverse pair condition.
  3. Count and merge both parts of the array while maintaining the order.

Code: