Question presented to candidate: "A message of letters A to Z was encoded as numbers, A = 1, B = 2, up to Z = 26, and the numbers were written next to each other with no separators. Given the digit string, count how many ways it can be decoded. Pay special attention to zeros โ what do you do with a string like '06' or '100'? Code it in Python."
What a strong answer should cover:
- The state:
dp[i]= number of ways to decode the firstidigits, withdp[0] = 1(the empty prefix has one decoding: nothing). - The two moves: the last letter used one digit (allowed only if that digit is not
0, adddp[i-1]) or two digits (allowed only if they form 10 to 26, adddp[i-2]). - The zero rules: a
0can never stand alone, so it must be the second digit of10or20;06is not a letter because a two-digit code cannot start with0;30,00or a leading0make the whole answer 0. - O(n) time and O(1) space with two rolling variables, compared with the exponential plain recursion (the all-
1string grows like Fibonacci). - Python details: comparing single characters (
s[i - 1] == "2" and s[i] <= "6") instead ofint(s[i-1:i+1])avoids building a slice each step, andint("06")returns 6, which is exactly the bug the question is fishing for.
Clarifying questions expected:
- Can the string contain zeros, and can it start with one?
- What should an empty string return?
- Can the answer be large โ should it be returned modulo something?
Code / implementation expected: Yes โ a one-pass Python DP with two rolling variables, tested on "06", "10", "100" and "226".