Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set.

Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set.
def pair_xor(a):
    total = 0
    for b in range(31):
        ones = sum(x >> b & 1 for x in a)
        total += ones * (len(a) - ones) << b
    return total
print(pair_xor([5, 9, 14, 3]))
What is printed?
  1. A. 26
  2. B. 59
  3. C. 48
  4. D. 31

Correct answer: B. 59

A bit contributes 2^b once for each pair where exactly one number has it: ones × zeros pairs. For [5, 9, 14, 3] that sums to 59, matching the six pairwise XORs added directly.

More Coding Interview Problems questions

Exams that ask this topic