Data Structures & AlgorithmsModerateTCS NQT Digital · counting

Problem: How many strings of length 4 over {a, b} contain neither 'aa' nor 'bb' as a substring? Run the code.

Problem: How many strings of length 4 over {a, b} contain neither 'aa' nor 'bb' as a substring? Run the code.
from itertools import product
print(sum(1 for t in product('ab', repeat=4) if all(t[i] != t[i + 1] for i in range(3))))
What is printed?
  1. A. 4
  2. B. 3
  3. C. 1
  4. D. 2

Correct answer: D. 2

Adjacent letters must differ, so once the first letter is chosen every later letter is forced: 2 × 1 × 1 × 1 = 2 strings, abab and baba. Answering 1 forgets that the string may start with either letter, and 4 wrongly gives some later position a free choice.

More Coding Interview Problems questions

Exams that ask this topic