Number of Perfect Pairs Problem
Description
LeetCode Problem 3649.
You are given an integer array nums.
A pair of indices (i, j) is called perfect if the following conditions are satisfied:
i < j- Let
a = nums[i],b = nums[j]. Then:min(|a - b|, |a + b|) <= min(|a|, |b|)max(|a - b|, |a + b|) >= max(|a|, |b|)
Return the number of distinct perfect pairs.
Note: The absolute value |x| refers to the non-negative value of x.
Example 1:
Input: nums = [0,1,2,3]
Output: 2
Explanation:
There are 2 perfect pairs:
(i, j) (a, b) min(|a − b|, |a + b|) min(|a|, |b|) max(|a − b|, |a + b|) max(|a|, |b|)
(1, 2) (1, 2) min(|1 − 2|, |1 + 2|) = 1 1 max(|1 − 2|, |1 + 2|) = 3 2
(2, 3) (2, 3) min(|2 − 3|, |2 + 3|) = 1 2 max(|2 − 3|, |2 + 3|) = 5 3
Example 2:
Input: nums = [-3,2,-1,4]
Output: 4
Explanation:
There are 4 perfect pairs:
(i, j) (a, b) min(|a − b|, |a + b|) min(|a|, |b|) max(|a − b|, |a + b|) max(|a|, |b|)
(0, 1) (-3, 2) min(|-3 - 2|, |-3 + 2|) = 1 2 max(|-3 - 2|, |-3 + 2|) = 5 3
(0, 3) (-3, 4) min(|-3 - 4|, |-3 + 4|) = 1 3 max(|-3 - 4|, |-3 + 4|) = 7 4
(1, 2) (2, -1) min(|2 - (-1)|, |2 + (-1)|) = 1 1 max(|2 - (-1)|, |2 + (-1)|) = 3 2
(1, 3) (2, 4) min(|2 - 4|, |2 + 4|) = 2 2 max(|2 - 4|, |2 + 4|) = 6 4
Example 3:
Input: nums = [1,10,100,1000]
Output: 0
Explanation:
There are no perfect pairs. Thus, the answer is 0.
Constraints:
2 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Sort by Absolute Value + Two Pointers
Let x <= y be the absolute values of the two numbers. Then min(|a - b|, |a + b|) = y - x and max(|a - b|, |a + b|) = x + y, whichever signs a and b have. The second condition x + y >= y always holds, so the pair is perfect exactly when y - x <= x, that is, y <= 2x.
Signs no longer matter and only the pair of indices does, so sort the absolute values. For each r, the values a[l..r-1] that satisfy 2 * a[l] >= a[r] form a suffix of the prefix before r, because a is sorted. Move l right while 2 * a[l] < a[r] (l never moves back, since a[r] only grows), and add r - l to the answer.
Complexity: O(n log n) time for the sort and O(n) extra space.
class Solution:
def perfectPairs(self, nums: List[int]) -> int:
a = sorted(abs(x) for x in nums)
ans = l = 0
for r, y in enumerate(a):
while a[l] * 2 < y:
l += 1
ans += r - l
return ans