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 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.

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
Number of Excellent PairsInputnums = [1, 2, 3, 5]k = 5ProcessCheck pairs: bits(a|b) + bits(a&b) >= kUse property: = bits(a) + bits(b)Bit Count Analysis1: 1 bit, 2: 1 bit, 3: 2 bits, 5: 2 bitsValid pairs (sum >= 5): (1,5), (2,5), (3,5), (5,5)Example: (3,5) → 2+2=4 < 5 ✗, but (5,5) → 2+2=4 ≥ 5 ✓Output: 4Count of excellent pairs
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
Asked in
Google 12 Meta 8 Microsoft 6
18.5K Views
Medium Frequency
~35 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen