Data Structures & AlgorithmsModerateTCS NQT · bit operations

Problem: How many pairs (i < j) of [1, 2, 3, 4, 5] have a[i] XOR a[j] = 1? Run the code.

Problem: How many pairs (i < j) of [1, 2, 3, 4, 5] have a[i] XOR a[j] = 1? Run the code.
a = [1, 2, 3, 4, 5]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] ^ a[j] == 1))
What is printed?
  1. A. 1
  2. B. 3
  3. C. 2
  4. D. 4

Correct answer: C. 2

The pairs (2,3) and (4,5) differ only in the lowest bit, so they XOR to 1.

More Coding Interview Problems questions

Exams that ask this topic