Data Structures & AlgorithmsModerateTCS NQT · counting

Problem: How many strings of length 3 over the alphabet {a, b, c} have no two equal adjacent characters? Run the code.

Problem: How many strings of length 3 over the alphabet {a, b, c} have no two equal adjacent characters? Run the code.
from itertools import product
print(sum(1 for t in product('abc', repeat=3) if t[0] != t[1] and t[1] != t[2]))
What is printed?
  1. A. 18
  2. B. 6
  3. C. 27
  4. D. 12

Correct answer: D. 12

The first letter has 3 choices, each next letter has 2 choices, giving 3 * 2 * 2 = 12. The trap 18 comes from allowing the first and third letter to match.

More Coding Interview Problems questions

Exams that ask this topic