Ctrl K

Pairs With Enough Set Bits

Hard
You are given an array of positive integers codes and an integer need. An ordered pair of values (x, y) is **strong** if both values appear in codes and popcount(x OR y) + popcount(x AND y) ≥ need, where popcount is the number of 1 bits in the binary form and OR / AND are the bitwise operations. x and y may be the same value: the pair (x, x) only requires x to appear in the array at least once. Return the number of distinct strong pairs. Pairs (a, b) and (c, d) are distinct when a ≠ c or b ≠ d, so (1, 2) and (2, 1) are counted separately. Repeated values in the array do not create extra pairs.
Example 1
codes=[5, 6, 1], need=4 → 4

5 (101) and 6 (110) have two set bits each. For (5, 6): 5 OR 6 = 111, 5 AND 6 = 100, so 3 + 1 = 4. The pairs (5, 5), (5, 6), (6, 5) and (6, 6) qualify; any pair involving 1 scores at most 3.

Example 2
codes=[3, 3, 8], need=3 → 3

Repeats add no new pairs: the only values are 3 and 8. (3, 3), (3, 8) and (8, 3) qualify, while (8, 8) scores only 1 + 1 = 2.

Example 3
codes=[7], need=7 → 0
Constraints
  • 1 ≤ len(codes) ≤ 10⁵
  • 1 ≤ codes[i] ≤ 10⁹
  • 1 ≤ need ≤ 60
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsThe Lost Ticket EasyTriples With a Zero AND HardSquare-Sum Chains HardWords That Fit Each Puzzle HardTurn Every Lamp Off Hard
loading Python…
Input
codes=[5, 6, 1], need=4
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 110 tests on the server, hidden ones included.