Python coding

Ways to read a digit code

A message in capital letters was encoded by replacing each letter with its position in the English alphabet (A → 1, B → 2, …, Z → 26) and writing the numbers with no separators. Given the digit string code, return how many different messages could have produced it. No number starts with 0: "06" can't be read as F, and "0" on its own is not a letter.

code has 1 to 60 digits; return 0 when no message fits. Aim for one pass.

Besides the tests, one large input (a 30-digit code) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • count_readings("226") → 3
  • count_readings("11106") → 2
  • count_readings("06") → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Let ways[i] count the readings of the first i digits. The last letter of a reading uses either the last digit or the last two.

Hint 2

Add ways[i - 1] when code[i - 1] is not 0, and ways[i - 2] when code[i - 2:i] is between 10 and 26. Start from ways[0] = 1: the empty prefix reads one way.

Hint 3

Only the last two counts matter, as in Fibonacci. A 0 can only close a 10 or a 20, so "30" breaks every reading.

Solution and why it works
pythonO(n) · O(1)
def count_readings(code: str) -> int:
    prev, cur = 0, 1                     # readings of code[:i - 1] and code[:i]; the empty prefix reads one way
    for i, d in enumerate(code):
        ways = cur if d != "0" else 0    # d read as a letter on its own
        if i > 0 and "10" <= code[i - 1:i + 1] <= "26":
            ways += prev                 # the last two digits read as one letter
        prev, cur = cur, ways
    return cur

Every reading ends with a one-digit or a two-digit letter, and what comes before is a reading of a shorter prefix, so ways[i] = ways[i - 1] + ways[i - 2] when each piece is valid: Fibonacci with conditions, O(n) with two counts. Plain recursion branches twice per digit, exponential on "1111…". The traps are the zeros and the range: "0" is never a letter alone and "30" is not a letter, so "301" has no reading, while "27" is two letters, never one.

Related lab: Big-O growth