Data Structures & AlgorithmsModerateProduct Company SDE · CP practice

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

Problem: How many strings of length 5 over {a, b, c} have no two adjacent equal characters? Run the code.
from itertools import product
print(sum(1 for t in product('abc', repeat=5) if all(t[i] != t[i + 1] for i in range(4))))
What is printed?
  1. A. 48
  2. B. 243
  3. C. 32
  4. D. 24

Correct answer: A. 48

3 choices for the first letter and 2 for each of the next 4: 3 · 2⁴ = 48. 3⁵ = 243 ignores the rule, 2⁵ = 32 gives the first letter 2 choices, and 3 · 2³ = 24 misses one step.

More Coding Interview Problems questions

Exams that ask this topic