#3649

Number of Perfect Pairs

Medium
ArrayMathTwo PointersSortingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

Sort the array by absolute values and use a two-pointer technique to efficiently count valid pairs that meet the conditions.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array based on absolute values.
  2. 2Step 2: Use two pointers to find pairs (i, j) such that the conditions are satisfied.
  3. 3Step 3: Count valid pairs while moving the pointers appropriately.
solution.py10 lines
1def perfectPairs(nums):
2    nums.sort(key=abs)
3    count = 0
4    n = len(nums)
5    j = 0
6    for i in range(n):
7        while j < n and abs(nums[j]) <= 2 * abs(nums[i]):
8            j += 1
9        count += j - i - 1
10    return count

Complexity note: The sorting step takes O(n log n), and the two-pointer traversal is O(n), making it efficient overall.

  • 1Sorting helps in efficiently finding valid pairs.
  • 2Using two pointers reduces the need for nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.