Data Structures & AlgorithmsHardTCS NQT Digital · counting

Problem: How many ordered pairs (i, j) with i != j of [1, 2, 3, 4] have an even sum? Run the code.

Problem: How many ordered pairs (i, j) with i != j of [1, 2, 3, 4] have an even sum? Run the code.
a = [1, 2, 3, 4]
print(sum(1 for i in range(4) for j in range(4) if i != j and (a[i] + a[j]) % 2 == 0))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 6
  4. D. 8

Correct answer: B. 4

The unordered even-sum pairs are (1,3) and (2,4), and each gives 2 ordered pairs, for 4 in total.

More Coding Interview Problems questions

Exams that ask this topic