Taro Logo

Number of Perfect Pairs

Medium
Asked by:
Squarepoint Capital
1 view
Topics:
ArraysTwo PointersBinary Search

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 <= 105
  • -109 <= nums[i] <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. Can the array contain negative numbers or zeros, and how does the minimum or maximum calculation behave in those cases?
  2. How large can the input array `nums` be, and what is the expected range of the integer values within it?
  3. Are duplicate values allowed in the input array, and if so, should identical elements at different indices be treated as distinct pairs?
  4. Does the condition `i <= j` mean we are considering pairs of indices rather than values, meaning a single element paired with itself is valid if it satisfies the conditions?
  5. What should be the return type and value if the input array is empty or contains only a single element?

Brute Force Solution

Approach

Imagine you have a collection of items and you need to count how many pairs of them match a specific condition of perfection. The brute force approach involves examining every possible pairing one by one to see if they fit the criteria.

Here's how the algorithm would work step-by-step:

  1. Gather all the items you need to examine.
  2. Select the first item from your collection to be the starting point of your first pair.
  3. Compare this first item against every other item in the collection, one by one.
  4. For every comparison, check if the two items together form a perfect pair according to the rules.
  5. If they make a perfect pair, make a mental note to count it later.
  6. Once you have compared your starting item with every other item, move on to the next item in the collection and repeat the process.
  7. Continue this exhaustive comparison for every single item until every possible combination has been checked.
  8. Finally, tally up all the mental notes you made to get the total number of perfect pairs.

Code Implementation

def count_perfect_pairs(collection):    total_perfect_pairs = 0    collection_length = len(collection)    # We iterate through each item to serve as the fixed starting point for our pair combinations    for starting_index in range(collection_length):        starting_item = collection[starting_index]        # We compare the current starting item against all subsequent items to evaluate every unique pairing        for comparison_index in range(starting_index + 1, collection_length):            comparison_item = collection[comparison_index]            # We verify the perfection condition using absolute differences and sums to match problem constraints            if abs(starting_item - comparison_item) <= abs(starting_item + comparison_item):                total_perfect_pairs += 1    return total_perfect_pairs

Big(O) Analysis

Time Complexity
O(n²) – For each of the n items in your collection acting as the starting point, the approach compares it against every other item in the collection one by one. This exhaustive comparison results in the first item being checked against n-1 items, the second item against n-2 items, and so on. Summing these comparisons leads to approximately n * n/2 total operations for all possible combinations. Finally, dropping the constant factor simplifies this growth rate to O(n²).
Space Complexity
O(N) – The algorithm relies on the plain English steps of gathering items into a collection and keeping a mental note or tally of valid combinations as it processes each pair. This requires allocating auxiliary variables and a tracking data structure, such as a hash map or list, to store intermediate results during the exhaustive comparisons. As the input size N increases, the number of stored mental notes and collection elements grows in direct proportion to N. Therefore, the auxiliary space complexity scales linearly with the input size, simplifying to O(N).

Optimal Solution

Approach

Instead of comparing every single item with every other item, the optimal approach groups similar items together and sorts them first. This clever organization allows us to count valid pairs quickly using simple arithmetic rather than checking every combination one by one.

Here's how the algorithm would work step-by-step:

  1. Gather all the given items and organize them by their size so that the smallest ones come first and the largest ones come at the end.
  2. Walk through the organized items one by one, treating each as the starting point of a potential pair.
  3. For the current item, look at all the items that come after it and figure out how far their sizes are from the current item.
  4. Use a mathematical shortcut to count how many of those subsequent items fall within the acceptable size limits, rather than checking each one individually.
  5. Add that count to your running total of valid pairs.
  6. Move on to the next item and repeat the process until you have considered every item as a starting point.
  7. Return the final accumulated count as the total number of valid pairs.

Code Implementation

def count_perfect_pairs(input_numbers):
    sorted_numbers = sorted(input_numbers)
    
    total_valid_pairs = 0
    total_elements = len(sorted_numbers)
    
    # Sorting allows us to establish boundaries and use math instead of nested brute-force scans.
    outer_pointer = 0
    while outer_pointer < total_elements:
        inner_pointer = outer_pointer
        
        while inner_pointer < total_elements and sorted_numbers[inner_pointer] <= sorted_numbers[outer_pointer] * 2:
            inner_pointer += 1
            
        # Mathematical shortcut calculates valid elements in range instantly instead of iterating.
        total_valid_pairs += (inner_pointer - outer_pointer - 1)
        outer_pointer += 1
        
    return total_valid_pairs

Big(O) Analysis

Time Complexity
O(n²) – Sorting the n items initially takes O(n log n) time, which is dominated by the subsequent pair-counting process. For each of the n items functioning as a starting point, we iterate through the remaining elements to calculate valid pairs based on size differences. This traversal and range checking requires inspecting subsequent items for each starting element. The work across all iterations accumulates to approximately n * n/2 operations, which simplifies in asymptotic analysis to O(n²).
Space Complexity
O(N) – The space complexity is driven by the sorting operation and any auxiliary collections used to organize the items by size, where N represents the total number of items. In a typical language runtime, the sorting algorithm requires O(N) or O(log N) auxiliary stack space to manage the partition or merge steps. Furthermore, storing the organized sequence of items requires extra memory proportional to the input size. Therefore, the total auxiliary space complexity simplifies to Big O of N.

Edge Cases

Empty or single-element array
How to Handle:
Return zero immediately since no valid pairs of indices can be formed.
Array containing negative numbers or zeros
How to Handle:
Since elements can be zero or negative, minimum and sum conditions must account for sign behavior to avoid division-by-zero or incorrect comparisons.
Arrays with all identical values
How to Handle:
Sorting or frequency counting handles identical elements in batch to compute combinations efficiently without $O(N^2)$ overhead.
Extremely large inputs up to maximum constraints
How to Handle:
An $O(N og N)$ sorting and two-pointer or binary search approach must be used to avoid Time Limit Exceeded errors from naive $O(N^2)$ looping.
Integer overflow during sum operations
How to Handle:
Use 64-bit integer types for calculating sums and differences when array values approach standard integer limits.
Pairs where i equals j
How to Handle:
The condition i <= j includes self-pairs, so valid elements that satisfy the inequalities with themselves must be counted.
Widely skewed value distributions
How to Handle:
Monotonic properties after sorting allow the use of sliding windows to efficiently bound the search space for each element.
No valid perfect pairs exist in the array
How to Handle:
The algorithm simply completes its traversal and correctly returns a total count of zero.