KatInterview

Count Pairs Whose XOR Has Exactly K Set Bits

Math & Bit ManipulationAuto-graded · 17 test cases
MediumAuto-gradedMath & Bit Manipulationbit manipulationnumber theorycombinatorics

Last updated

Tests the ability to combine bit counting (popcount) with efficient pair enumeration to find pairs in an array whose XOR contains exactly K set bits.

Count Pairs Whose XOR Has Exactly K Set Bits

Given a list of non-negative integers nums and a non-negative integer k, count the number of unordered pairs (i, j) with i < j such that the bitwise XOR of nums[i] and nums[j] has exactly k set bits (i.e., its popcount equals k).

Background

The popcount (population count) of an integer is the number of 1-bits in its binary representation. For example:

  • popcount(0b1011) = 3
  • popcount(0b1100) = 2

The XOR of two integers flips every bit position where the two values differ. So popcount(a XOR b) counts the number of bit positions where a and b differ.

Task

Implement count_xor_pairs(nums, k) that returns the count of unordered pairs (i, j) with i < j such that bin(nums[i] ^ nums[j]).count('1') == k.

Constraints

  • 0 ≤ len(nums) ≤ 2000
  • 0 ≤ nums[i] ≤ 10^6
  • 0 ≤ k ≤ 20
  • Pairs are unordered: (i, j) and (j, i) count as one pair.
  • If len(nums) < 2, return 0.
  • Duplicate values in nums are allowed; each index is treated as a distinct element.

Examples

Example 1

Input: count_xor_pairs([3, 5, 7, 1], 2)

Output: 2

Example 2

Input: count_xor_pairs([0, 0, 0], 0)

Output: 3

Example 3

Input: count_xor_pairs([1, 2, 4, 8], 2)

Output: 6

Hints

Hint 1

XOR of two numbers has a 1-bit exactly where the two numbers differ; popcount(a ^ b) counts those differing positions.

Hint 2

A brute-force O(n²) scan over all pairs is sufficient for n ≤ 2000; Python's int.bit_count() (3.10+) or bin(x).count('1') gives popcount in O(1) for bounded values.

Hint 3

Group values by their popcount in a frequency map, then combine groups whose popcounts can XOR to give exactly k set bits — but be careful: popcount(a ^ b) ≠ popcount(a) XOR popcount(b), so straightforward grouping alone does not work without extra care.