Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26.

Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26.
def decode(s):
    prev2, prev1 = 1, (1 if s[0] != '0' else 0)
    for i in range(1, len(s)):
        cur = 0
        if s[i] != '0': cur += prev1
        if 10 <= int(s[i-1:i+1]) <= 26: cur += prev2
        prev2, prev1 = prev1, cur
    return prev1
print(decode("226"), decode("2101"), decode("06"), decode("1111"))
What is printed?
  1. A. 3 1 0 5
  2. B. 3 2 0 5
  3. C. 3 1 1 5
  4. D. 2 1 0 5

Correct answer: A. 3 1 0 5

One digit is valid unless it is 0; two digits are valid if 10..26. "226" → 2-2-6, 22-6, 2-26. "2101": the 0 must pair as 10, then 1 alone: 2-10-1 only. "06" has no valid start. "1111" gives Fibonacci 5. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic