21 minute read

A deceptive counting problem that teaches the fundamentals of state transitions, the same structure behind sequence decoding in speech recognition.

TL;DR

Use DP where dp[i] counts valid decodings of the first i characters. Check both single-digit (1-9) and two-digit (10-26) decodings at each position, treating zeros carefully since 0 has no standalone mapping. Optimize to O(1) space by tracking only two previous values. This state-transition pattern is the foundation of sequence DP problems like Word Break, and with probabilities instead of counts it becomes the forward and Viterbi algorithms used in CTC speech recognition.

Problem

A message containing letters from A-Z can be encoded into numbers using the following mapping:

  • ‘A’ -> “1”
  • ‘B’ -> “2”
  • …
  • ‘Z’ -> “26”

To decode an encoded message, you need to group the digits and map them back to letters. Given a string s containing only digits, return the number of ways to decode it.

Example 1:

Input: s = "12"
Output: 2
Explanation: "12" could be decoded as "AB" (1 2) or "L" (12).

Example 2:

Input: s = "226"
Output: 3
Explanation: "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).

Example 3 (The Tricky One):

Input: s = "06"
Output: 0
Explanation: "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").

Constraints:

  • 1 <= s.length <= 100
  • s contains only digits and may contain leading zero(s).

Why This Problem Matters: Decoding Paths

Speech recognition and text generation also “decode”: they turn a sequence of model outputs into the most likely sequence of tokens.

  • Decode Ways: We count all valid paths.
  • Speech decoders: We score paths with probabilities and look for the best one (Viterbi or beam search), or sum over all of them (the CTC forward algorithm).

The underlying structure is a graph where each node represents a state (index in the string), and edges represent valid transitions (taking 1 digit or 2 digits). The section From Counting Paths to CTC and Beam Search makes the connection precise.

Approach 1: Brute Force Recursion

Let’s think about this recursively. At any index i, we have two choices:

  1. Single Digit: Take s[i] as a single number. Valid if s[i] is ‘1’-‘9’.
  2. Double Digit: Take s[i]s[i+1] as a two-digit number. Valid if it forms a number between 10 and 26.

Let numDecodings(i) be the number of ways to decode the suffix s[i:].

Recurrence Relation: numDecodings(i) = (valid single ? numDecodings(i+1) : 0) + (valid double ? numDecodings(i+2) : 0)

Base Cases:

  • If i == len(s): We reached the end successfully. Return 1.
  • If s[i] == '0': A string starting with ‘0’ cannot be decoded. Return 0.

Python Implementation (Recursive)

def numDecodings_recursive(s: str) -> int:
    def decode(index):
        # Base Case: End of string
        if index == len(s):
            return 1
        
        # Base Case: Leading zero
        if s[index] == '0':
            return 0
        
        # Option 1: Take 1 digit
        res = decode(index + 1)
        
        # Option 2: Take 2 digits
        if index + 1 < len(s) and (s[index] == '1' or (s[index] == '2' and s[index+1] in "0123456")):
            res += decode(index + 2)
            
        return res

    return decode(0)

Complexity Analysis

  • Time Complexity: Exponential. In the worst case (e.g., “111111”), every step branches into two, so the number of calls grows like the Fibonacci numbers, roughly O(1.62^N), which is bounded by O(2^N).
  • Space Complexity: O(N) for the recursion stack.

Approach 2: Recursion with Memoization

We are re-calculating the same subproblems. decode(5) might be called from decode(3) (taking 2 steps) and decode(4) (taking 1 step). We can cache the results.

def numDecodings_memo(s: str) -> int:
    memo = {}
    
    def decode(index):
        if index in memo:
            return memo[index]
        
        if index == len(s):
            return 1
        
        if s[index] == '0':
            return 0
        
        res = decode(index + 1)
        
        if index + 1 < len(s) and (s[index] == '1' or (s[index] == '2' and s[index+1] in "0123456")):
            res += decode(index + 2)
            
        memo[index] = res
        return res

    return decode(0)
  • Time Complexity: O(N). We visit each index once.
  • Space Complexity: O(N) for memoization map + stack.

Approach 3: Iterative Dynamic Programming

Let’s flip it. Instead of recursion, let’s build an array dp. dp[i] = Number of ways to decode the string s[0...i-1] (length i).

Initialization:

  • dp[0] = 1 (Empty string has 1 way: do nothing).
  • dp[1] = 1 if s[0] != '0' else 0.

Transitions: For i from 2 to n:

  1. One Digit: If s[i-1] is not ‘0’, we can add dp[i-1].
  2. Two Digits: If s[i-2:i] is between “10” and “26”, we can add dp[i-2].

Python Implementation (Iterative)

def numDecodings_dp(s: str) -> int:
    if not s or s[0] == '0':
        return 0
    
    n = len(s)
    dp = [0] * (n + 1)
    
    dp[0] = 1
    dp[1] = 1
    
    for i in range(2, n + 1):
        # Check if single digit is valid (1-9)
        if s[i-1] != '0':
            dp[i] += dp[i-1]
            
        # Check if two digits are valid (10-26)
        two_digit = int(s[i-2:i])
        if 10 <= two_digit <= 26:
            dp[i] += dp[i-2]
            
    return dp[n]

Complexity Analysis

  • Time Complexity: O(N).
  • Space Complexity: O(N) for the dp array.

Approach 4: Space Optimization (O(1) Space)

Notice that dp[i] only depends on dp[i-1] and dp[i-2]. We don’t need the whole array. We just need two variables.

def numDecodings_optimized(s: str) -> int:
    if not s or s[0] == '0':
        return 0
    
    n = len(s)
    two_back = 1 # dp[i-2] (initially dp[0])
    one_back = 1 # dp[i-1] (initially dp[1])
    
    for i in range(2, n + 1):
        current = 0
        
        # Single digit check
        if s[i-1] != '0':
            current += one_back
            
        # Double digit check
        two_digit = int(s[i-2:i])
        if 10 <= two_digit <= 26:
            current += two_back
            
        two_back = one_back
        one_back = current
        
    return one_back
  • Space Complexity: O(1).

Detailed Walkthrough: Tracing “226”

Let’s trace the O(1) space algorithm with s = "226".

Initialization:

  • two_back (dp[0]) = 1 (empty prefix)
  • one_back (dp[1]) = 1 (since ‘2’ != ‘0’)

Iteration 1 (i=2, Char=’2’):

  • Single Digit: ‘2’ is valid. current += one_back (1).
  • Double Digit: “22” is valid (10-26). current += two_back (1).
  • current = 2.
  • Update: two_back = 1, one_back = 2.
  • Meaning: “22” can be “BB” or “V”.

Iteration 2 (i=3, Char=’6’):

  • Single Digit: ‘6’ is valid. current += one_back (2).
  • Double Digit: “26” is valid (10-26). current += two_back (1).
  • current = 3.
  • Update: two_back = 2, one_back = 3.
  • Meaning: “226” can be “BBF”, “VF”, “BZ”.

Result: Return 3.

Edge Cases and Pitfalls

This problem is famous for its edge cases.

  1. Leading Zeros: “06” -> 0. “0” -> 0.
  2. Mid-stream Zeros: “10” -> 1 (“J”). “100” -> 0 (The second ‘0’ cannot be decoded alone, and “00” is invalid).
  3. Large Numbers: “30” -> 0. “27” -> 1 (“BG”, not “27”).

Debugging Tip: If your code fails on “10”, check if you handle the single digit case correctly. s[i-1] is ‘0’, so you shouldn’t add dp[i-1]. But s[i-2:i] is “10”, which is valid, so you add dp[i-2].

Advanced Variant: Decode Ways II (Wildcards)

What if the input string contains * (LeetCode 639)?

  • * can be any digit from ‘1’ to ‘9’.
  • 1* can be “11” to “19” (9 possibilities).
  • 2* can be “21” to “26” (6 possibilities).
  • ** can be “11”-“19” and “21”-“26” (15 possibilities).
  • *d for a digit d: “1d” is always a letter, “2d” only when d is 0-6, so 2 possibilities for d in 0-6 and 1 for d in 7-9.

The running time stays O(N); what grows is the count, so the problem asks for the answer modulo 10^9 + 7. The DP is unchanged except that each transition gets a coefficient: the number of ways to read the last character alone, and the number of ways to read the last two characters as one letter.

def numDecodings_II(s: str) -> int:
    MOD = 10**9 + 7

    def one(c):        # ways to read c as a single letter
        if c == '*': return 9
        return 0 if c == '0' else 1

    def two(a, b):     # ways to read "ab" as one letter (10-26)
        if a == '*' and b == '*': return 15          # 11-19, 21-26
        if a == '*': return 2 if b <= '6' else 1     # 1b and 2b, or only 1b
        if b == '*':
            return 9 if a == '1' else 6 if a == '2' else 0
        return 1 if 10 <= int(a + b) <= 26 else 0

    two_back, one_back = 1, one(s[0])                # dp[0], dp[1]
    for i in range(1, len(s)):
        current = (one(s[i]) * one_back + two(s[i-1], s[i]) * two_back) % MOD
        two_back, one_back = one_back, current
    return one_back

print(numDecodings_II("*"), numDecodings_II("1*"), numDecodings_II("2*"))  # 9 18 15

This version was checked against brute-force expansion of every * on 1,500 random strings.

Decode Ways is a DP over a small directed acyclic graph: the nodes are positions 0 to n, and there is an edge from i to i+1 or i+2 when that one- or two-digit chunk maps to a letter. Counting decodings sums over every path. Change what sits on the edges and how paths are combined where they meet, and you get the core algorithms of sequence decoding:

Edge weight Combine paths with Algorithm Answers
1 sum Decode Ways How many segmentations exist
Probability sum Forward algorithm Total probability of all paths
Probability max Viterbi The single most likely path
Probability that depends on the whole history keep top K Beam search An approximately best path

CTC (Connectionist Temporal Classification), used to train many speech recognition models, is the clearest example. The acoustic model outputs a distribution over tokens plus a special blank symbol at every audio frame. A frame-level path maps to a transcript by merging repeated tokens and then removing blanks, so h h _ e _ l _ l l o and h _ e e l _ l o both become “hello”. A blank is required between the two l’s; without it they would merge into one.

Training needs the total probability of all frame-level paths that collapse to the reference transcript. Enumerating them is exponential, so the CTC loss uses a forward DP over the transcript with blanks interleaved, where each state is reached from at most three predecessors. Structurally that is Decode Ways with probabilities on the edges and sums where paths join.

Decoding goes the other way. Greedy CTC decoding takes the best token at each frame and collapses the result. Beam search keeps the K highest-scoring partial transcripts at every frame; the CTC prefix beam search variant merges paths that collapse to the same prefix by summing their probabilities, exactly the “sum where paths join” step above, and can add a language-model score for each word. Exact DP stops being practical once the score depends on the entire history (a neural language model conditions on every previous token), because the number of distinct states explodes. That is when beam search’s pruning becomes necessary. See ASR Beam Search Implementation for a full CTC decoder and Beam Search Decoding for the text-generation side.

Interview Simulation

Interviewer: “Can you solve this in constant space?” You: “Yes. dp[i] only needs dp[i-1] and dp[i-2], the same Fibonacci-like structure, so two variables are enough.”

Interviewer: “What if the mapping included ‘’ which can be 1-9?” You: “That’s LeetCode 639 (Decode Ways II). The logic is the same, but the branching factor increases. ‘’ as a single digit adds 9 * dp[i-1], ‘**’ adds 15 * dp[i-2], and the answer is taken modulo 10^9 + 7.”

Interviewer: “How would you test this?” You: “I would use a table of test cases covering all zero-patterns:

  • Start: ‘0’, ‘01’
  • Middle: ‘101’, ‘100’, ‘20’, ‘30’
  • End: ‘10’
  • Valid: ‘12’, ‘226’”

Interviewer: “Can you write a test suite?” You: “Sure. I’d use a data-driven test.”

def test_decode_ways():
    cases = [
        ("12", 2),
        ("226", 3),
        ("0", 0),
        ("06", 0),
        ("10", 1),
        ("27", 1),
        ("2101", 1) # B J A
    ]
    for s, expected in cases:
        assert numDecodings_optimized(s) == expected
        print(f"Pass: {s} -> {expected}")

Multi-Language Implementation

C++

class Solution {
public:
    int numDecodings(string s) {
        if (s.empty() || s[0] == '0') return 0;
        int n = s.length();
        vector<int> dp(n + 1, 0);
        dp[0] = 1;
        dp[1] = 1;
        
        for (int i = 2; i <= n; ++i) {
            int oneDigit = s[i-1] - '0';
            int twoDigits = stoi(s.substr(i-2, 2));
            
            if (oneDigit >= 1) dp[i] += dp[i-1];
            if (twoDigits >= 10 && twoDigits <= 26) dp[i] += dp[i-2];
        }
        return dp[n];
    }
};

Java

class Solution {
    public int numDecodings(String s) {
        if (s == null || s.length() == 0 || s.charAt(0) == '0') return 0;
        int n = s.length();
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;
        
        for (int i = 2; i <= n; i++) {
            int oneDigit = Integer.valueOf(s.substring(i-1, i));
            int twoDigits = Integer.valueOf(s.substring(i-2, i));
            
            if (oneDigit >= 1) dp[i] += dp[i-1];
            if (twoDigits >= 10 && twoDigits <= 26) dp[i] += dp[i-2];
        }
        return dp[n];
    }
}

Go

// requires: import "strconv"
func numDecodings(s string) int {
    if len(s) == 0 || s[0] == '0' {
        return 0
    }
    n := len(s)
    dp := make([]int, n+1)
    dp[0] = 1
    dp[1] = 1
    
    for i := 2; i <= n; i++ {
        oneDigit := s[i-1] - '0'
        twoDigits, _ := strconv.Atoi(s[i-2 : i])
        
        if oneDigit >= 1 {
            dp[i] += dp[i-1]
        }
        if twoDigits >= 10 && twoDigits <= 26 {
            dp[i] += dp[i-2]
        }
    }
    return dp[n]
}

Rust

impl Solution {
    pub fn num_decodings(s: String) -> i32 {
        if s.starts_with('0') {
            return 0;
        }
        let n = s.len();
        let chars: Vec<char> = s.chars().collect();
        let mut dp = vec![0; n + 1];
        dp[0] = 1;
        dp[1] = 1;
        
        for i in 2..=n {
            let one_digit = chars[i-1].to_digit(10).unwrap();
            let two_digits = s[i-2..i].parse::<i32>().unwrap();
            
            if one_digit >= 1 {
                dp[i] += dp[i-1];
            }
            if two_digits >= 10 && two_digits <= 26 {
                dp[i] += dp[i-2];
            }
        }
        dp[n]
    }
}

Appendix A: Parallel Version with Transition Matrices

Can very long inputs be split across workers? dp[i] depends on dp[i-1], which looks sequential, but each step is a linear map:

[dp[i], dp[i-1]] = M_i × [dp[i-1], dp[i-2]], with M_i = [[a, b], [1, 0]], where a = 1 if s[i-1] is not ‘0’ and b = 1 if s[i-2:i] is between 10 and 26.

Matrix multiplication is associative, so you can split the string into chunks, multiply each chunk’s matrices independently, and combine the chunk products in order with a parallel reduction (the same idea as a parallel prefix scan). Each M_i reads s[i-2:i], so a chunk only needs one character of overlap with its left neighbor. Order matters: matrix products are not commutative.

def step_matrix(s, i):
    """M with [dp[i], dp[i-1]] = M @ [dp[i-1], dp[i-2]], for 2 <= i <= len(s)."""
    a = 1 if s[i-1] != '0' else 0
    b = 1 if 10 <= int(s[i-2:i]) <= 26 else 0
    return ((a, b), (1, 0))

def matmul(X, Y):
    return tuple(tuple(sum(X[r][k] * Y[k][c] for k in range(2)) for c in range(2)) for r in range(2))

def numDecodings_matrix(s: str) -> int:
    if not s or s[0] == '0':
        return 0
    P = ((1, 0), (0, 1))
    for i in range(2, len(s) + 1):  # any contiguous run of steps can be multiplied on its own
        P = matmul(step_matrix(s, i), P)
    return P[0][0] + P[0][1]        # applied to [dp[1], dp[0]] = [1, 1]

print(numDecodings_matrix("226"))  # 3

For a 100-character interview input this is pure overhead; it only pays off for very long digit streams.

Appendix B: Proof of the Recurrence

Let N(S) be the number of ways to decode string S. Let S be d_1 d_2 ... d_n.

We claim that N(S) satisfies the recurrence: N(S[1...n]) = C_1 * N(S[2...n]) + C_2 * N(S[3...n])

Proof: The first decision is disjoint and exhaustive.

  1. Case 1: We decode d_1 as a single character. This is valid if d_1 is between 1 and 9. If valid, the remaining problem is S[2...n]. The number of ways is 1 * N(S[2...n]).
  2. Case 2: We decode d_1 d_2 as a single character. This is valid if d_1 d_2 is between 10 and 26. If valid, the remaining problem is S[3...n]. The number of ways is 1 * N(S[3...n]).

Since these are the only two ways to consume the start of the string, by the Rule of Sum, the total ways is the sum of these two cases. So the count for a string depends only on the counts for its suffixes, which is what makes the DP correct.

Appendix C: Test Cases by Category

When testing your solution, ensure you cover these categories:

Category 1: Basic Valid

  1. “1” -> 1 (A)
  2. “12” -> 2 (AB, L)
  3. “226” -> 3 (BZ, VF, BBF)
  4. “111” -> 3 (AAA, AK, KA)

Category 2: Leading Zeros

  1. “0” -> 0
  2. “01” -> 0
  3. “00” -> 0
  4. “012” -> 0

Category 3: Trailing Zeros

  1. “10” -> 1 (J)
  2. “20” -> 1 (T)
  3. “30” -> 0 (Invalid)
  4. “100” -> 0 (Invalid)

Category 4: Middle Zeros

  1. “101” -> 1 (JA)
  2. “1001” -> 0
  3. “110” -> 1 (AJ: “1” “10”; “11” “0” is invalid)

Category 5: Boundary Conditions

  1. “26” -> 2 (BF, Z)
  2. “27” -> 1 (BG)
  3. “9” -> 1 (I)
  4. “99” -> 1 (II)

Appendix D: Common Dynamic Programming Patterns

“Decode Ways” is a sequence DP: the state is a position in the input. Here are other classic DP patterns worth knowing:

  1. 0/1 Knapsack:
    • Problem: Pick items with weight w and value v to maximize value within capacity W.
    • State: dp[i][w] = Max value using first i items with capacity w.
    • Transition: max(dp[i-1][w], dp[i-1][w-w_i] + v_i).
  2. Longest Increasing Subsequence (LIS):
    • Problem: Find the longest subsequence where elements are increasing.
    • State: dp[i] = Length of LIS ending at index i.
    • Transition: dp[i] = 1 + max(dp[j]) for all j < i where nums[j] < nums[i].
  3. Longest Common Subsequence (LCS):
    • Problem: Find the longest subsequence common to two strings.
    • State: dp[i][j] = LCS of s1[0..i] and s2[0..j].
    • Transition: If s1[i] == s2[j], 1 + dp[i-1][j-1]. Else max(dp[i-1][j], dp[i][j-1]).
  4. Matrix Chain Multiplication (interval DP):
    • Problem: Parenthesize matrix multiplications to minimize scalar operations.
    • State: dp[i][j] = Min cost to multiply matrices i through j.
    • Transition: min(dp[i][k] + dp[k+1][j] + cost(i, k, j)) for all k.

Conclusion

Decode Ways is a masterclass in handling state transitions and edge cases. It teaches you to look beyond the “happy path” and rigorously define valid transitions.

Key Takeaways:

  1. Zeros are the enemy. Handle them first.
  2. State Definition: dp[i] depends on i-1 and i-2.
  3. Optimization: Space can be reduced to O(1).

Practice Problems:

FAQ

How do you solve the Decode Ways problem?

Use dynamic programming where dp[i] represents the number of ways to decode the first i characters. If the current digit is valid (1-9), add dp[i-1]. If the two-digit number formed with the previous digit is valid (10-26), add dp[i-2]. Handle zeros carefully since they have no standalone mapping. Base cases are dp[0] = 1 (empty string has one decoding) and dp[1] = 1 if the first character is not zero.

Why are zeros tricky in Decode Ways?

Zero cannot be decoded alone since no letter maps to 0. It must pair with a preceding 1 or 2 to form 10 or 20. If zero follows any other digit (like 30, 40, etc.), the string is invalid and the total number of decodings is zero. This makes zero handling the most common source of bugs in implementations.

What is the space-optimized solution for Decode Ways?

Since dp[i] depends only on dp[i-1] and dp[i-2], replace the full array with two variables (prev1 and prev2). At each step, compute the new value from these two, then shift the variables forward. This reduces space from O(N) to O(1) while maintaining O(N) time complexity, identical to the Fibonacci optimization pattern.

How does Decode Ways relate to beam search?

Decode Ways counts every path through a small graph whose nodes are string positions and whose edges are valid one- or two-digit chunks. Put probabilities on the edges and sum over paths, and you get the forward algorithm that computes the CTC loss in speech recognition; take the maximum instead and you get Viterbi decoding. Beam search approximates the best path when the score depends on the whole history (for example a neural language model), because exact DP then has too many states.