As reported: LinkedIn online assessment (Feb 2025), on HackerRank: two problems in 90 minutes; perfect pairs was the first, needing
O(n log n)(sorting and two pointers). The same question came up in a LinkedIn technical screening (Feb 2025), with the follow-up: can it beatO(n²)?
You are given an integer array nums. A pair of indices (i, j) with i < j is perfect if, with a = nums[i] and b = nums[j]:
min(|a − b|, |a + b|) ≤ min(|a|, |b|), andmax(|a − b|, |a + b|) ≥ max(|a|, |b|).
Return the number of perfect pairs.
This is LeetCode 3649 — Number of Perfect Pairs.
Example 1
nums = [0,1,2,3]
Output: 2 ((1,2) and (2,3))
Example 2
nums = [-3,2,-1,4]
Output: 4
Example 3
nums = [1,10,100,1000]
Output: 0
Example 4
nums = [2,-3,5]
Output: 2 ((2,-3) and (-3,5))
Constraints: 2 ≤ nums.length ≤ 10^5; −10^9 ≤ nums[i] ≤ 10^9.
Code runner format: LeetCode's test-case format, one JSON value per line (one line per argument). Implement perfectPairs(nums); the harness prints the result (it can exceed 32 bits).