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?- A. 18
- B. 6
- C. 27
- 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
- Problem: How many divisors does 720 have? Run the code. python print(sum(1 for d in range(1, 721) if 720 % d == 0)) What is printed?
- Problem: How many ways are there to decode the digit string '111' (1 maps to A, ..., 26 maps to Z)? Run the DP. python s = '111' dp = [1]…
- Problem: What is the length of the longest substring without repeating characters in 'pwwkew'? Run the sliding-window code. python s =…
- Problem: How many distinct permutations (rearrangements as strings) of 'aabc' exist? Run the code. python from itertools import…
- Problem: What is the sum of C(10, k) over all even k from 0 to 10? Run the code. python from math import comb print(sum(comb(10, k) for k…
- Problem: How many integers in [100, 999] have all three digits distinct? Run the code. python print(sum(1 for x in range(100, 1000) if…