Data Structures & AlgorithmsVery hardProduct company OA

Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and the other does not.

Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and the other does not.
def xor_pair_sum(a):
    total = 0
    for b in range(max(a).bit_length()):
        ones = sum(x >> b & 1 for x in a)
        total += ones * (len(a) - ones) << b
    return total
a = [5, 9, 7, 6]
print(xor_pair_sum(a), sum(a[i] ^ a[j] for i in range(4) for j in range(i + 1, 4)))
What is printed?
  1. A. 47 47
  2. B. 47 94
  3. C. 38 47
  4. D. 94 94

Correct answer: A. 47 47

5 = 0101, 9 = 1001, 7 = 0111, 6 = 0110. Bit 0: three ones → 3·1 pairs × 1 = 3; bit 1: two ones → 2·2 × 2 = 8; bit 2: three → 3 × 4 = 12; bit 3: one → 3 × 8 = 24; total 47, matching the O(n²) brute force. Counting ordered pairs would double it (94). O(n log max) handles n = 2·10⁵.

More Coding Interview Problems questions

Exams that ask this topic