Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the bits that differ between two IDs (Hamming distance) and the total over all pairs of an array.

Problem: Count the bits that differ between two IDs (Hamming distance) and the total over all pairs of an array.
def ham(x, y): return bin(x ^ y).count('1')
def total(a):
    n, t = len(a), 0
    for b in range(32):
        ones = sum((v >> b) & 1 for v in a)
        t += ones * (n - ones)
    return t
print(ham(1, 4), total([4, 14, 2]))
What is printed?
  1. A. 1 6
  2. B. 2 4
  3. C. 3 6
  4. D. 2 6

Correct answer: D. 2 6

1 = 001, 4 = 100 → 2 differing bits. For all pairs, each bit contributes (ones × zeros) pairs: 4 = 0100, 14 = 1110, 2 = 0010 → bit1: 2 ones → 2, bit2: 2 ones → 2, bit3: 1 one → 2; total 6 = ham(4,14) + ham(4,2) + ham(14,2) = 2 + 2 + 2. O(32·n) instead of O(n²).

More Coding Interview Problems questions

Exams that ask this topic