Data Structures & AlgorithmsHardTCS NQT · Product Company OA

Problem: What is the sum of a[i] XOR a[j] over all pairs i < j of [1, 2, 3, 4]? Run the code.

Problem: What is the sum of a[i] XOR a[j] over all pairs i < j of [1, 2, 3, 4]? Run the code.
a = [1, 2, 3, 4]
print(sum(a[i] ^ a[j] for i in range(len(a)) for j in range(i + 1, len(a))))
What is printed?
  1. A. 20
  2. B. 18
  3. C. 24
  4. D. 30

Correct answer: C. 24

The six XORs are 1^2 = 3, 1^3 = 2, 1^4 = 5, 2^3 = 1, 2^4 = 6 and 3^4 = 7, which total 24. Adding the pair sums instead of XORing gives 30, and XOR is not addition: 1 ^ 3 = 2, not 4.

More Coding Interview Problems questions

Exams that ask this topic