Reverse Pairs

Given an integer array `nums`, return the number of reverse pairs in the array. A reverse pair is a pair `(i, j)` where: - `0 <= i < j < nums.length` and - `nums[i] > 2 * nums[j]`.

30:00

Reverse Pairs
hard
Free written solution
Topics
Companies

Given an integer array nums, return the number of reverse pairs in the array.

A reverse pair is a pair (i, j) where:

  • 0 <= i < j < nums.length and
  • nums[i] > 2 * nums[j].
Example 1:
Input: {"nums":[1,3,2,3,1]}
Output: 2
Constraints:
  • 1≤nums.length≤5×1041 \leq \text{nums.length} \leq 5 \times 10^4

  • −231≤nums[i]≤231−1-2^{31} \leq \text{nums}[i] \leq 2^{31} - 1

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,3,2,3,1]}

Merge sort the array. Before merging two sorted halves, count pairs with a left-half value greater than twice a right-half value.

nums

1
3
2
3
1

0

1

2

3

4

total pairs

0

Variables
VariableValue
n5
DepthFunction Call
Stack empty
0/14