Taro Logo

Number of Excellent Pairs

Hard
Asked by:
epiFi
0 views
Topics:
ArraysTwo PointersBinary SearchBit Manipulation

You are given a 0-indexed positive integer array nums and a positive integer k.

A pair of numbers (num1, num2) is called excellent if the following conditions are satisfied:

  • Both the numbers num1 and num2 exist in the array nums.
  • The sum of the number of set bits in num1 OR num2 and num1 AND num2 is greater than or equal to k, where OR is the bitwise OR operation and AND is the bitwise AND operation.

Return the number of distinct excellent pairs.

Two pairs (a, b) and (c, d) are considered distinct if either a != c or b != d. For example, (1, 2) and (2, 1) are distinct.

Note that a pair (num1, num2) such that num1 == num2 can also be excellent if you have at least one occurrence of num1 in the array.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: 5
Explanation: The excellent pairs are the following:
- (3, 3). (3 AND 3) and (3 OR 3) are both equal to (11) in binary. The total number of set bits is 2 + 2 = 4, which is greater than or equal to k = 3.
- (2, 3) and (3, 2). (2 AND 3) is equal to (10) in binary, and (2 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.
- (1, 3) and (3, 1). (1 AND 3) is equal to (01) in binary, and (1 OR 3) is equal to (11) in binary. The total number of set bits is 1 + 2 = 3.
So the number of excellent pairs is 5.

Example 2:

Input: nums = [5,1,1], k = 10
Output: 0
Explanation: There are no excellent pairs for this array.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 60

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 input array contain duplicate numbers, and if so, should identical values at different index positions be treated as distinct pairs?
  2. How should we handle pairs where $i = j$ (i.e., pairing an element with itself)?
  3. What are the expected value ranges for the elements in the array and the threshold integer?
  4. What does "distinct pairs of indices $(i, j)$" mean regarding symmetry—is the pair $(i, j)$ considered the same as $(j, i)$?
  5. What should be returned if no pairs meet the set bits threshold condition?

Brute Force Solution

Approach

Imagine you have a collection of numbers and want to find every possible pair where a special mathematical condition is met. The brute force approach simply examines every single possible pair of numbers available, one by one, to see if it satisfies the requirement.

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

  1. Gather all the distinct numbers from your collection so you are not repeating yourself unnecessarily.
  2. Pick the first number in your collection and pair it with every other number available, including itself.
  3. For each of these pairs, perform the required mathematical checks to see if the combined result meets the target threshold.
  4. Keep a running count of how many pairs pass this test successfully.
  5. Move on to the next number in your collection and repeat the process of pairing it with every other number.
  6. Continue this systematic checking for every single combination until no new pairs are left to test.
  7. Finally, share the total count of successful pairs you found during your exhaustive search.

Code Implementation

def count_excellent_pairs(number_list, threshold):
    distinct_numbers = list(set(number_list))

    # We eliminate duplicates first to ensure we only process unique pairs exactly once
    excellent_pairs_count = 0

    for first_index in range(len(distinct_numbers)):
        for second_index in range(len(distinct_numbers)):
            first_value = distinct_numbers[first_index]
            second_value = distinct_numbers[second_index]

            bitwise_or_result = first_value | second_value
            bitwise_and_result = first_value & second_value

            or_set_bits = bin(bitwise_or_result).count('1')
            and_set_bits = bin(bitwise_and_result).count('1')

            # Bit manipulation mimics the set-bit counting requirement for the threshold check
            if (or_set_bits + and_set_bits) >= threshold:
                excellent_pairs_count += 1

    # Return the accumulated total after exhaustively checking every single distinct pair
    return excellent_pairs_count

Big(O) Analysis

Time Complexity
O(n²) – First, we remove duplicates to get a collection of distinct numbers of size up to n. Then, we iterate through each of these distinct numbers using an outer loop and pair it with every other number using an inner loop to check the condition. For the first number we check all elements, for the second we check one less, creating a sequence of comparisons. This sums to approximately n * n/2 total pair checks, which simplifies to a final time complexity of O(n²).
Space Complexity
O(N) – The algorithm requires auxiliary space to store the distinct numbers from the collection and to build a frequency map of their set bits. In the worst case where all N elements in the input are unique, the set and the frequency array will store up to N elements. Therefore, the extra memory required scales linearly with the input size N, resulting in a linear auxiliary space complexity.

Optimal Solution

Approach

The problem asks for the number of distinct pairs of numbers whose bitwise OR and bitwise AND have a combined set bit count of at least k. Using the bitwise identity, the sum of set bits in (a OR b) and (a AND b) is identical to the sum of set bits in a plus set bits in b. Consequently, the condition reduces to finding pairs of unique numbers whose individual popcounts add up to at least k.

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

  1. Eliminate duplicate elements from nums using a set because pairs are defined by distinct number values.
  2. Calculate the number of set bits for each unique value.
  3. Sort the computed set bit counts in non-decreasing order.
  4. Employ a two-pointer technique to count how many pairs have a sum of set bit counts greater than or equal to k.
  5. Accumulate the count of valid second elements for each first element and return the final total.

Code Implementation

def count_excellent_pairs(nums: list[int], k: int) -> int:
    # Remove duplicate values since pairs must be distinct combinations of numbers
    unique_numbers = set(nums)
    # Count the set bits for each unique number in the array
    bit_counts = sorted(number.bit_count() for number in unique_numbers)
    total_pairs = 0
    total_unique = len(bit_counts)
    right_index = total_unique - 1
    # Use a two-pointer approach to find pairs with sum of set bits at least k
    for left_index in range(total_unique):
        while right_index >= 0 and bit_counts[left_index] + bit_counts[right_index] >= k:
            right_index -= 1
        # All elements from right_index + 1 to the end form valid pairs
        valid_count = total_unique - (right_index + 1)
        total_pairs += valid_count
    return total_pairs

Big(O) Analysis

Time Complexity
O(N log U + U log U) – Extracting unique elements and computing their set bits takes O(N) where N is the length of nums. Sorting the U unique bit counts takes O(U log U) where U is at most N. The two-pointer traversal takes O(U) time.
Space Complexity
O(U) – A set and a list are stored to hold the distinct numbers and their corresponding bit counts, requiring space proportional to U, the number of unique elements.

Edge Cases

Array contains duplicate numbers
How to Handle:
Using a sorted unique elements array with frequency counting prevents duplicate pair generation and simplifies the index logic.
Array with a single element
How to Handle:
The loop boundaries or pair constraints will naturally yield zero since at least two elements are required to form a pair.
Threshold is zero
How to Handle:
All possible pairs will satisfy the condition since any pair has at least zero set bits, so the answer is combinations of n items taken two at a time plus n.
Threshold is larger than the maximum possible set bits
How to Handle:
The algorithm will correctly compare the bit counts and return zero since no pair meets the excessively high threshold.
Maximum-sized inputs with up to 10 to the 5th elements and large values
How to Handle:
Converting the problem to operate on the sum of set bits of individual numbers using bit manipulation reduces the time complexity to O(n log n) with sorting.
Values with identical bit counts
How to Handle:
Using two pointers on a sorted array of set bit counts correctly aggregates all valid combinations in linear time after sorting.
Language-specific integer overflow during bit operations
How to Handle:
Standard 32-bit or 64-bit integers easily accommodate the bit lengths up to 10 to the 9th without exceeding limits.
Self pairs where i equals j
How to Handle:
The problem permits identical indices if the bit count of num AND num plus num OR num is at least the threshold, which simplifies to twice the set bits of num.