Data Structures & AlgorithmsHardProduct Company SDE · DP round

Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP.

Problem: How many ways can the digit string '226' be decoded when 1 maps to A, 2 to B, ..., 26 to Z? Run the DP.
s = '226'
dp = [1] * (len(s) + 1)
for i in range(2, len(s) + 1):
    cur = 0
    if s[i - 1] != '0':
        cur += dp[i - 1]
    if 10 <= int(s[i - 2:i]) <= 26:
        cur += dp[i - 2]
    dp[i] = cur
print(dp[len(s)])
What is printed?
  1. A. 2
  2. B. 4
  3. C. 1
  4. D. 3

Correct answer: D. 3

The decodings are BBF (2,2,6), BZ (2,26) and VF (22,6), so there are 3. A zero digit alone cannot be decoded, which is why the code checks s[i - 1] != '0'.

More Coding Interview Problems questions

Exams that ask this topic