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?- A. 1 6
- B. 2 4
- C. 3 6
- 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
- Problem: A permissions mask is an int; report how many permissions (set bits) each mask grants. java static int popc(int x) { return…
- Problem: Enumerate all subsets of a small item list using bitmasks and count subsets with even sum. python a = [3, 4, 5, 6] cnt = 0 for…
- Problem: Find the missing number in an array containing n distinct values from 0..n. python def missing(a): x = len(a) for i, v in…
- Problem: Compute 2⁴⁰ mod (10⁹ + 7) by fast power in Java (long arithmetic). java static long power(long b, long e, long m) { long r = 1; b…
- Problem: Sum the remainders of a list of signed deltas modulo 3 in C++ and in Python. cpp int a = -7 % 3; int b = 7 % -3; int c = ((-7 %…
- Problem: Sum the prices of n = 100000 items, each 50000, in Java. java int n = 100000, price = 50000; int total = n price; long total2 = n…