Data Structures & AlgorithmsModerateCodeforces Div2 B · bit operations

Problem: Count pairs (i < j) of a = [1, 2, 3] with a[i] XOR a[j] summed over all pairs. What is the total of the XOR values? Run the code.

Problem: Count pairs (i < j) of a = [1, 2, 3] with a[i] XOR a[j] summed over all pairs. What is the total of the XOR values? Run the code.
a = [1, 2, 3]
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. 6
  2. B. 12
  3. C. 9
  4. D. 3

Correct answer: A. 6

The pairs give 1 XOR 2 = 3, 1 XOR 3 = 2 and 2 XOR 3 = 1, which sum to 6. Adding the pair sums instead gives 12, using OR (every pair gives 3) gives 9, and using AND gives 0 + 1 + 2 = 3.

More Coding Interview Problems questions

Exams that ask this topic