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 numbers
num1andnum2exist in the arraynums - The sum of the number of set bits in
num1 OR num2andnum1 AND num2is greater than or equal to k
Here's the key insight: For any two numbers a and b, the number of set bits in (a OR b) + the number of set bits in (a AND b) equals the number of set bits in a + the number of set bits in b. This transforms our problem from complex bitwise operations to simple bit counting!
Goal: Return the number of distinct excellent pairs.
Important notes:
- Pairs
(a,b)and(c,d)are distinct if eithera != corb != d - Pairs like
(1,2)and(2,1)are considered different - A number can be paired with itself if it appears in the array
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,2,3,1], k = 3
โบ
Output:
5
๐ก Note:
Unique numbers are [1,2,3]. Check all pairs: (1,1): bits(1|1)+bits(1&1)=1+1=2<3 โ, (1,2): bits(1|2)+bits(1&2)=2+0=2<3 โ, (1,3): bits(1|3)+bits(1&3)=2+1=3โฅ3 โ, (2,1): 2+0=2<3 โ, (2,2): bits(2|2)+bits(2&2)=1+1=2<3 โ, (2,3): bits(2|3)+bits(2&3)=2+2=4โฅ3 โ, (3,1): 2+1=3โฅ3 โ, (3,2): 2+2=4โฅ3 โ, (3,3): bits(3|3)+bits(3&3)=2+2=4โฅ3 โ. Total: 5 pairs.
example_2.py โ All Pairs Excellent
$
Input:
nums = [5,1,1], k = 1
โบ
Output:
4
๐ก Note:
Unique numbers are [5,1]. Since k=1 is low, most pairs work: (5,5): bits(5)=2, 2+2=4โฅ1 โ, (5,1): bits(5)+bits(1)=2+1=3โฅ1 โ, (1,5): same as (5,1) โ, (1,1): bits(1)=1, 1+1=2โฅ1 โ. All 4 pairs are excellent.
example_3.py โ High Threshold
$
Input:
nums = [1,1,1,1], k = 10
โบ
Output:
0
๐ก Note:
Only unique number is 1. The pair (1,1) has bits(1|1)+bits(1&1)=1+1=2, which is less than k=10. No excellent pairs exist.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- 1 โค k โค 60
- Each number has at most 20 bits (since 220 > 109)
Visualization
Tap to expand
Understanding the Visualization
1
The Key Identity
For any two numbers, OR captures all set bits, AND captures common bits, and their sum equals the total individual bits
2
Frequency Mapping
Instead of checking each pair, group numbers by bit count and use multiplication
3
Mathematical Optimization
For each pair of bit counts summing to โฅk, multiply their frequencies
Key Takeaway
๐ฏ Key Insight: The mathematical identity `bits(a|b) + bits(a&b) = bits(a) + bits(b)` transforms an expensive bitwise problem into simple frequency counting and arithmetic, reducing complexity from O(nยฒ) to O(n).
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code