Count how many letter sequences a digit string can represent under the mapping from 1 through 26.
Problem
Input. A string text containing only ASCII digits.
Output. Return the number of complete decodings when tokens 1 through 26 represent letters A through Z.
Rules. Every digit must belong to exactly one valid token, in its original order.
A token cannot start with zero; 10 and 20 are valid, but 0 and 06 are not.
Return zero for empty input by this API’s convention. The reference assumes, rather than validates, ASCII digits.
Example. "12" returns 2, representing "AB" and "L".
For "2101", return 1 for "BJA"; "06" returns 0.
Picture
Boundary means consumed digits.
Before processing index i, one_back counts text[:i] and two_back counts text[:i-1].
A valid current single digit extends every one-back parse.
A valid pair from 10 through 26 extends every two-back parse.
These groups cannot overlap because their last token widths differ.
| Prefix | Valid final-token contributions | Count |
|---|---|---|
2 | one initial token | 1 |
21 | single 1, pair 21 | 2 |
210 | pair 10 only | 1 |
2101 | single 1; pair 01 invalid | 1 |
The answer is 2 | 10 | 1, or BJA.
Compute current before shifting both older values together.
Initialization uses one empty-prefix parse internally, despite the separate external empty-input policy.
Problem trace
Add disjoint parse groups only when their final token is valid
- index 0
- 0
- prefix
- "2"
- state
- two_back = 1; one_back = 1
- index 1
- 0→1
- prefix
- "2"→"21"
- arithmetic
- not shown→single 1 + pair 1 = 2
- index 2
- 1→2
- prefix
- "21"→"210"
- arithmetic
- single 1 + pair 1 = 2→single 0 + pair 1 = 1
- index 3
- 2→3
- prefix
- "210"→"2101"
- arithmetic
- single 0 + pair 1 = 1→single 1 + invalid pair 0 = 1
- Recognize it
- Use it when each encoded token consumes one or two adjacent symbols, validity depends on the local symbol or pair, and the task asks for the number of complete parses.
- Keep true
- Before index i, one_back counts decodings through i-1 and two_back through i-2; current sums exactly the valid single-digit and two-digit ways ending at i.
- Reuse it
- For variable-width parsing, sum counts from earlier boundaries only when the token ending at the current boundary is valid; zeros often eliminate the width-one transition.
Reference drawing
Problem trace
Add disjoint parse groups only when their final token is valid
Execution trace
- index 0
- 0
- prefix
- "2"
- state
- two_back = 1; one_back = 1
- index 1
- 0→1
- prefix
- "2"→"21"
- arithmetic
- not shown→single 1 + pair 1 = 2
- index 2
- 1→2
- prefix
- "21"→"210"
- arithmetic
- single 1 + pair 1 = 2→single 0 + pair 1 = 1
- index 3
- 2→3
- prefix
- "210"→"2101"
- arithmetic
- single 0 + pair 1 = 1→single 1 + invalid pair 0 = 1
- Recognize it
- Use it when each encoded token consumes one or two adjacent symbols, validity depends on the local symbol or pair, and the task asks for the number of complete parses.
- Keep true
- Before index i, one_back counts decodings through i-1 and two_back through i-2; current sums exactly the valid single-digit and two-digit ways ending at i.
- Reuse it
- For variable-width parsing, sum counts from earlier boundaries only when the token ending at the current boundary is valid; zeros often eliminate the width-one transition.
Code
def num_decodings(text: str) -> int:
if not text or text[0] == "0":
return 0
two_back = one_back = 1
for index in range(1, len(text)):
current = one_back if text[index] != "0" else 0
if 10 <= int(text[index - 1 : index + 1]) <= 26:
current += two_back
two_back, one_back = one_back, current
return one_back
The loop uses additions and a constant number of integer slots. Growing counts mean neither constant bit storage nor constant-time additions is guaranteed.
Failure Check
06 and 100 have zero complete decodings; 10 has one.
Accepting zero alone invents parses.
Overwriting an older count before both contributions are computed loses a dependency.
Change to Decoded Witnesses
New task: Return every decoded letter string for small inputs.
Picture and change: Branch on valid widths one and two, then prepend the corresponding letter to completed suffix witnesses.
def decoded_strings(text):
if not text or not text.isascii() or not text.isdecimal():
return []
def visit(index):
if index == len(text):
return [""]
result = []
for width in (1, 2):
token = text[index:index + width]
if len(token) == width and token[0] != "0" and 1 <= int(token) <= 26:
for suffix in visit(index + width):
result.append(chr(64 + int(token)) + suffix)
return result
return visit(0)
Check: "226" returns ["BBF","BZ","VF"]; "06" returns [].
The internal completed suffix contributes one empty string, not zero witnesses.
Enumeration can require exponentially many output characters and recursive calls.
It does not inherit the source’s constant integer-slot storage or avoid Python’s recursion limit.
Use when: Actual decodings are needed and their output is small.
Change the Token Vocabulary
New task: Count parses from an arbitrary finite set of nonempty strings.
Picture and change: Keep one count per prefix boundary and add earlier counts only for valid ending slices.
def codebook_parse_count(text, tokens):
tokens = set(tokens)
if "" in tokens:
raise ValueError("empty token")
ways = [1] + [0] * len(text)
for end in range(1, len(text) + 1):
for token in tokens:
if len(token) <= end and text[end - len(token):end] == token:
ways[end] += ways[end - len(token)]
return ways[-1]
Check: "123" with ["1","2","3","12","123"] has three parses: 1|2|3, 12|3 and 123.
Duplicate tokens do not multiply parses; empty tokens are rejected.
This generic API counts empty text as one empty parse.
Its cost includes token comparisons, slicing, growing integer additions and the full boundary-count row.
Use when: Validity no longer means decimal values from one through twenty-six.
Transfer Check
What changes when only parse existence is needed?
Answer
Replace count addition with Boolean OR while retaining the same valid-token boundary edges. Witnesses and counts need different output evidence.