Data Structures19 sections · 729 units
Open in Course

Problem - Reverse Pairs

Variant of inversion counting

Given an integer array nums, count the number of reverse pairs: indices (i,j)(i, j) where i<ji < j and nums[i]>2nums[j]nums[i] > 2 \cdot nums[j]. Example: nums =[1,3,2,3,1]= [1, 3, 2, 3, 1] returns 22.

Reverse pairs: (1,4)(1, 4) since 3>213 > 2 \cdot 1, and (3,4)(3, 4) since 3>213 > 2 \cdot 1.

This is similar to inversions, but the condition is a[i]>2a[j]a[i] > 2 \cdot a[j] instead of a[i]>a[j]a[i] > a[j]. Approach: process right to left, query for elements less than a[i]/2a[i] / 2. Constraints: up to 51045 \cdot 10^4 elements, values up to 23112^{31} - 1.