ProgrammingVery hardTCS NQT · Accenture

A message of digits is decoded by mapping 1 to A, 2 to B, ..., 26 to Z, where a digit string may be split into one- or two-digit groups. The number of decodings of "1212" is computed by the standard DP below. What is printed?

A message of digits is decoded by mapping 1 to A, 2 to B, ..., 26 to Z, where a digit string may be split into one- or two-digit groups. The number of decodings of "1212" is computed by the standard DP below. What is printed?
dp[0] = 1 (empty prefix); dp[1] = 1 if s[0] != '0'
for i = 2 to n
    if s[i-1] != '0' then dp[i] += dp[i-1]
    if 10 <= value(s[i-2..i-1]) <= 26 then dp[i] += dp[i-2]
end for
Print dp[n]
  1. A. 1
  2. B. 3
  3. C. 5
  4. D. 8

Correct answer: C. 5

The decodings of 1212 are 1-2-1-2, 12-1-2, 1-21-2, 1-2-12 and 12-12, which is 5. Counting the valid two-digit windows gives 3, and counting every split of the three gaps gives 8.

More Pseudocode and Code Tracing questions

Exams that ask this topic