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: 0
💡 Note: No pairs have sufficient set bits. For any pair (a,b) from [1,2,3,5], the maximum sum of set bits in (a|b) and (a&b) is 4, which is less than k=5.
Example 2 — All Pairs Valid
$ Input: nums = [5,1,3], k = 3
Output: 8
💡 Note: All pairs except (1,1) are excellent. 1 has 1 bit, 3 has 2 bits, 5 has 2 bits. Valid pairs: (1,3)→3, (1,5)→3, (3,1)→3, (3,3)→4, (3,5)→4, (5,1)→3, (5,3)→4, (5,5)→4. Total: 8 pairs.
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 Pairs INPUT nums array: 1 2 3 5 Binary (Set Bits): 1 = 001 (1 bit) 2 = 010 (1 bit) 3 = 011 (2 bits) 5 = 101 (2 bits) Input Values nums = [1,2,3,5] k = 5 Find pairs where bits(OR) + bits(AND) >= k ALGORITHM STEPS 1 Key Property bits(OR) + bits(AND) = bits(num1) + bits(num2) 2 Group by Bit Count Count nums with same bits Bit Count | Numbers | Count 1 bit | 1, 2 | 2 2 bits | 3, 5 | 2 3 Find Valid Pairs bits(a) + bits(b) >= 5 4 Count Pairs 2+2=4: (3,3),(3,5),(5,3),(5,5) Need 2+3=5 or 3+2=5 etc. Only 2-bit pairs work! FINAL RESULT Excellent Pairs Found: (3, 3) 2+2=4 [OK] (3, 5) 2+2=4 [OK] (5, 3) 2+2=4 [OK] (5, 5) 2+2=4 [OK] Output 4 Excellent Pairs Key Insight: The identity bits(A OR B) + bits(A AND B) = bits(A) + bits(B) transforms the problem. Group unique numbers by their bit count, then count pairs where sum of bit counts >= k. Time: O(n log max) for counting bits | Space: O(log max) for bit count groups TutorialsPoint - Number of Excellent Pairs | Bit Count Grouping Approach
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