Ways to Decode a Numeric String into Letters
Dynamic ProgrammingAuto-graded · 24 test casesLast updated
Tests dynamic programming reasoning on sequential digit-to-letter mappings, including careful handling of zeros and invalid two-digit pairs.
Problem
You have a cipher that maps positive integers to letters: 1 → 'a', 2 → 'b', …, 26 → 'z'.
Given a non-empty string s made up of digit characters '0' through '9', return the total number of distinct ways to split s into a sequence of one- or two-digit tokens where each token maps to a valid letter.
A token is valid if:
- It is a single digit from
'1'to'9', or - It is a two-digit number from
10to26.
The digit '0' can never form a valid token on its own. A two-digit token whose first digit is '0' (such as "05") is also invalid.
If no valid splitting exists, return 0.
Constraints
1 <= len(s) <= 100sconsists only of the characters'0'–'9'- The answer fits in a 32-bit signed integer for inputs of this length
Examples
Example 1
Input: count_decodings('12')
Output: 2
Example 2
Input: count_decodings('226')
Output: 3
Example 3
Input: count_decodings('06')
Output: 0
Example 4
Input: count_decodings('11106')
Output: 2
Hints
Hint 1
Think about the number of ways to decode the string ending at each position. How does the count at position i relate to the counts at the two positions before it?
Hint 2
There are only two ways the last token of any decoding can look: a single digit, or a two-digit number. Check whether each is valid before adding its contribution.
Hint 3
A lone '0' has no valid single-digit mapping, and a pair like '30' or '00' falls outside the 10–26 range. Once any prefix becomes impossible, the count stays zero for all later positions — no special early-exit is needed for correctness.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
Define dp[i] as the number of valid decodings of the first i characters of s. Every such decoding ends with either a one-digit token (s[i-1]) or a two-digit token (s[i-2:i]). These two cases are mutually exclusive and together cover every possibility, so:
dp[i] = (single-digit contribution) + (two-digit contribution)
- Single-digit contribution:
s[i-1]is a valid standalone token if and only if it is not'0'. When valid, it addsdp[i-1]ways. - Two-digit contribution:
s[i-2:i]is valid when it falls in the range"10"to"26"(string comparison works here because both operands are exactly two digits, so lexicographic order matches numeric order). When valid, it addsdp[i-2]ways.
Base cases
dp[0] = 1: the empty prefix has exactly one decoding — the empty sequence. This is what lets a valid opening pair like"12"count at all.dp[1] = 1ifs[0] != '0', otherwise0.
Handling zeros
Zeros are the main source of mistakes:
'0'on its own is always rejected by the single-digit gate (s[i] != '0').- A pair like
"00"or"30"falls outside"10"–"26"and is rejected by the two-digit gate. "10"and"20"are the only pairs ending in zero that pass the gate.- A leading
'0'in the input immediately setsdp[1] = 0. The pair gate at index 1 also fails because the pair starts with'0'(below"10"), so both rolling values become 0 and stay 0.
Space optimization
Each state depends only on the two preceding states — the same recurrence structure as Fibonacci. Two rolling variables (prev2 and prev1) replace the full array, reducing space to O(1).
Why it is correct
Every decoding of the first i characters ends in exactly one of two token lengths. Removing that final token is a bijection onto valid decodings of a strictly shorter prefix. The two sets are disjoint and exhaustive, so their counts sum without double-counting or omission. Induction on i with the base cases above establishes correctness.
Complexity
- Time: O(n) — one pass through the string, constant work per step.
- Space: O(1) — only two variables are maintained at any time.
Edge cases
| Input | Output | Reason |
|---|---|---|
"0" | 0 | Lone zero has no valid mapping |
"06" | 0 | Leading zero; "06" is not in the valid range |
"10" | 1 | Only decoding is 10 → 'j' |
"226" | 3 | 2+2+6, 22+6, 2+26 |
"11106" | 2 | Two valid splittings around the embedded "10" |
Reference solution
def count_decodings(s: str) -> int:
if not s:
return 0
# prev2 = dp[i-1], prev1 = dp[i] (rolling variables)
prev2 = 1
prev1 = 0 if s[0] == '0' else 1
for i in range(1, len(s)):
current = 0
# Single-digit token valid for '1'–'9'
if s[i] != '0':
current += prev1
# Two-digit token valid for '10'–'26'
if '10' <= s[i - 1:i + 1] <= '26':
current += prev2
prev2, prev1 = prev1, current
return prev1