← Back to Algorithms, page 5

algorithms-0086 · Medium mid

Decode ways: count how many ways a digit string can be decoded when 'A' maps to 1 through 'Z' to 26, handling zeros correctly.

Let ways(i) be the number of decodings of the first i digits. The last digit alone adds ways(i-1) if it is not '0', and the last two digits add ways(i-2) if they form a number from 10 to 26. Two running variables give O(n) time and O(1) space. Zeros are the trap: '0' can only appear as part of 10 or 20.

Full answer

Problem

A message of letters was encoded as digits with A = 1, ..., Z = 26. Given the digit string, return the number of ways to decode it. Return 0 if no decoding exists.

Example: "12" gives 2 (AB, L); "226" gives 3 (BBF, BZ, VF); "06" gives 0; "10" gives 1.

Constraints: 1 <= len(s) <= 100; digits only; the answer fits in a 32-bit integer.

Brute force

Recursively take one digit (if not 0) or two digits (if between 10 and 26) and recurse on the rest. Without memoization this is exponential, close to Fibonacci growth on strings of 1s and 2s.

Optimal approach

  1. If s starts with '0', return 0.
  2. prev2 = 1 (empty prefix), prev1 = 1 (first digit).
  3. For i from 2 to n: cur = 0; if s[i-1] != '0', add prev1; if 10 <= int(s[i-2:i]) <= 26, add prev2. Shift: prev2, prev1 = prev1, cur.
  4. Return prev1.

Why it works

Every decoding of the first i digits ends with a letter made of either the last digit or the last two digits. A single-digit letter must be 1 to 9, so a '0' cannot stand alone; a two-digit letter must be 10 to 26, which excludes leading zeros like "06". The two cases are disjoint, so their counts add. If both cases fail at some position, the count becomes 0 and stays 0, which correctly reports an invalid string.

Complexity

O(n) time, O(1) space.

Code

python
import random


def num_decodings(s):
    """'A'=1 ... 'Z'=26. ways(i) = ways(i-1) if s[i-1] != '0', plus ways(i-2) if s[i-2:i] is 10..26.
    O(n) time, O(1) space."""
    if not s:
        return 0
    prev2, prev1 = 1, 1                  # ways for "" and for the prefix so far
    if s[0] == "0":
        return 0
    for i in range(2, len(s) + 1):
        cur = 0
        if s[i - 1] != "0":
            cur += prev1
        if 10 <= int(s[i - 2:i]) <= 26:
            cur += prev2
        prev2, prev1 = prev1, cur
    return prev1


def brute(s):
    """Enumerate every split into 1- and 2-digit pieces."""
    if s == "":
        return 1
    total = 0
    if s[0] != "0":
        total += brute(s[1:])
        if len(s) >= 2 and int(s[:2]) <= 26:
            total += brute(s[2:])
    return total


if __name__ == "__main__":
    assert num_decodings("12") == 2                     # AB, L
    assert num_decodings("226") == 3                    # BBF, BZ, VF
    assert num_decodings("06") == 0 and num_decodings("100") == 0 and num_decodings("10") == 1
    assert num_decodings("") == 0
    rng = random.Random(86)
    for _ in range(2000):
        s = "".join(rng.choice("0122346789") for _ in range(rng.randint(1, 12)))
        assert num_decodings(s) == brute(s)
    print("all tests passed")

Save as b86_decode_ways.py and run python3 b86_decode_ways.py. It prints all tests passed (Python 3.13.5).

Edge cases

Leading zero (0). "00" or "30" (0). "10" and "20" (1 each). "100" (0, because the final 0 cannot attach). Long strings of 1s and 2s (Fibonacci growth). Empty string: this version returns 0 by convention; confirm with the interviewer.

Pattern

Fibonacci-style counting DP with validity conditions on each transition. Related: decode ways with a * wildcard (more cases, take a modulus), climbing stairs with broken steps, and counting valid splittings of a string under rules.

python
import random


def num_decodings(s):
    """'A'=1 ... 'Z'=26. ways(i) = ways(i-1) if s[i-1] != '0', plus ways(i-2) if s[i-2:i] is 10..26.
    O(n) time, O(1) space."""
    if not s:
        return 0
    prev2, prev1 = 1, 1                  # ways for "" and for the prefix so far
    if s[0] == "0":
        return 0
    for i in range(2, len(s) + 1):
        cur = 0
        if s[i - 1] != "0":
            cur += prev1
        if 10 <= int(s[i - 2:i]) <= 26:
            cur += prev2
        prev2, prev1 = prev1, cur
    return prev1


def brute(s):
    """Enumerate every split into 1- and 2-digit pieces."""
    if s == "":
        return 1
    total = 0
    if s[0] != "0":
        total += brute(s[1:])
        if len(s) >= 2 and int(s[:2]) <= 26:
            total += brute(s[2:])
    return total


if __name__ == "__main__":
    assert num_decodings("12") == 2                     # AB, L
    assert num_decodings("226") == 3                    # BBF, BZ, VF
    assert num_decodings("06") == 0 and num_decodings("100") == 0 and num_decodings("10") == 1
    assert num_decodings("") == 0
    rng = random.Random(86)
    for _ in range(2000):
        s = "".join(rng.choice("0122346789") for _ in range(rng.randint(1, 12)))
        assert num_decodings(s) == brute(s)
    print("all tests passed")

Rolling two-variable count with explicit zero rules, cross-checked against exhaustive splitting on random digit strings with many zeros.

Complexity

Time: O(n). Space: O(1). The wildcard variant has the same shape with more cases per step.

By level

Fresher: Derives the one-digit and two-digit cases and traces them on "226". Explains why "06" is not a valid letter.

Mid: Handles all zero cases, compresses to two variables, and tests strings like "100" and "2101". Extends to the wildcard variant with a modulus.

Senior: Treats the problem as counting accepted strings in a small automaton, which makes adding rules systematic. Discusses validating inputs early and the cost of listing all decodings.

Key points

  • Last letter is one digit or two digits
  • One digit must be 1 to 9
  • Two digits must be 10 to 26
  • Zero can only follow 1 or 2
  • Two variables are enough

Common mistakes

  • Treating '0' as a valid single letter
  • Accepting "06" as a two-digit letter
  • Wrong initial values for the empty prefix
  • Not returning 0 once the count drops to 0

Follow-ups

  • How do you handle a '*' that can be any digit 1 to 9?
  • How would you list the decodings?
  • How would you answer modulo 10^9 + 7 for long inputs?

Tips

  • List the zero cases before coding
  • Trace "226" and "100"
  • State the empty-string convention

Evaluation rubric

  • Correct recurrence
  • Correct zero handling
  • O(1) space
  • Tests tricky inputs