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]- A. 1
- B. 3
- C. 5
- 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.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- A polynomial rolling hash of the string "abc" is computed as h = (h 31 + value) mod 1000, starting from h = 0, where value is the position…
- The string "bca" may have exactly one swap of two characters made. The procedure below finds the lexicographically smallest string…
- The phrase "the cat and the hat" is searched for the whole word "the" (counted as a separate word). The procedure below counts the…
- Strings are run-length compressed. The procedure below counts the number of runs in "aaabbc" (a run is a maximal block of equal…
- The procedure below checks the bracket string "(()())" and prints the maximum nesting depth it reaches. The depth is raised by '(' and…
- The sentence "to be or not to be to" is split into words, and the procedure below prints the most frequent word (ties go to the first word…