Data Structures & AlgorithmsModerateTCS NQT · counting

Problem: How many distinct products a[i] a[j] (i < j) does [1, 2, 3, 4] produce? Run the code.

Problem: How many distinct products a[i] * a[j] (i < j) does [1, 2, 3, 4] produce? Run the code.
from itertools import combinations
print(len({x * y for x, y in combinations([1, 2, 3, 4], 2)}))
What is printed?
  1. A. 5
  2. B. 6
  3. C. 4
  4. D. 3

Correct answer: B. 6

combinations gives the 6 pairs (i < j) and their products 2, 3, 4, 6, 8, 12 are all different, so the set keeps 6. A collision such as 1 × 4 = 2 × 2 would need an element paired with itself, which combinations never produces.

More Coding Interview Problems questions

Exams that ask this topic