Data Structures & AlgorithmsVery hardProduct Company SDE · CP practice

Problem: How many 4-letter words over {x, y, z} contain at least one letter from each of the three symbols? Run the code.

Problem: How many 4-letter words over {x, y, z} contain at least one letter from each of the three symbols? Run the code.
from itertools import product
print(sum(1 for t in product('xyz', repeat=4) if len(set(t)) == 3))
What is printed?
  1. A. 81
  2. B. 36
  3. C. 33
  4. D. 78

Correct answer: B. 36

Inclusion-exclusion: 3⁴ − 3 · 2⁴ + 3 · 1⁴ = 81 − 48 + 3 = 36 (= 3! · S(4,3)). 81 counts all words, skipping the + 3 gives 33, and 78 counts words with at least two letters.

More Coding Interview Problems questions

Exams that ask this topic