Number of Excellent Pairs Problem
Description
LeetCode Problem 2354.
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
num1andnum2exist in the arraynums. - The sum of the number of set bits in
num1 OR num2andnum1 AND num2is greater than or equal tok, whereORis the bitwise OR operation andANDis 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 <= 10^51 <= nums[i] <= 10^91 <= k <= 60
Solution
Approach: Count by Number of Set Bits
For any two numbers, popcount(a OR b) + popcount(a AND b) = popcount(a) + popcount(b). So a pair is excellent exactly when the sum of the two popcounts is at least k, and only the popcounts matter. Pairs of equal numbers add nothing new, so first remove duplicates ((a, b) and (b, a) are different pairs, and (a, a) counts when 2 * popcount(a) >= k).
Count how many distinct numbers have each popcount (at most 30 distinct values for nums[i] <= 10^9, so a small array). For every distinct number with popcount t, add the counts of all popcounts i with t + i >= k.
Complexity: O(n + B2) time, where B is the number of bits (about 30), and O(n) space for the set.
from collections import Counter
class Solution:
def countExcellentPairs(self, nums: List[int], k: int) -> int:
s = set(nums)
ans = 0
cnt = Counter()
for v in s:
cnt[bin(v).count('1')] += 1
for v in s:
t = bin(v).count('1')
for i, x in cnt.items():
if t + i >= k:
ans += x
return ans