Number of Excellent Pairs - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,2,3,5], k = 5
›
Output:
4
💡 Note:
Pairs (1,5), (2,5), (3,5), (5,5) have bit sums >= 5. For (3,5): bits(3|5) + bits(3&5) = bits(7) + bits(1) = 3 + 1 = 4 < 5, but (5,5): bits(5|5) + bits(5&5) = bits(5) + bits(5) = 3 + 3 = 6 >= 5.
Example 2 — All Pairs Valid
$
Input:
nums = [5,1,3], k = 3
›
Output:
5
💡 Note:
All pairs except (1,1) are excellent. 1 has 1 bit, 3 has 2 bits, 5 has 2 bits. Valid: (1,3), (1,5), (3,1), (3,5), (5,5).
Example 3 — No Valid Pairs
$
Input:
nums = [1,2], k = 5
›
Output:
0
💡 Note:
Maximum bit sum is 1+1=2 for (1,2), which is less than k=5. No excellent pairs exist.
Constraints
- 1 ≤ nums.length ≤ 105
- 1 ≤ nums[i] ≤ 109
- 1 ≤ k ≤ 60
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array of numbers and threshold k
2
Process
Find pairs where bits(a|b) + bits(a&b) >= k
3
Output
Count of excellent pairs
Key Takeaway
🎯 Key Insight: Use the mathematical property bits(a|b) + bits(a&b) = bits(a) + bits(b) to avoid expensive bitwise operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code