Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

Problem: How many pairs (i < j) of [1, 2, 3, 4, 5, 7] have an odd product?

Problem: How many pairs (i < j) of [1, 2, 3, 4, 5, 7] have an odd product?
a = [1, 2, 3, 4, 5, 7]
print(sum(1 for i in range(len(a)) for j in range(i + 1, len(a)) if a[i] * a[j] % 2 == 1))
What is printed?
  1. A. 6
  2. B. 9
  3. C. 12
  4. D. 4

Correct answer: A. 6

A product is odd only when both factors are odd; the 4 odd values 1, 3, 5, 7 give C(4,2) = 6 pairs. Counting even products gives 15 − 6 = 9, counting ordered pairs gives 12, and counting odd elements instead of pairs gives 4.

More Coding Interview Problems questions

Exams that ask this topic