Skip to content
mlmentorship

Add parse counts only for valid final tokens

Separate one-digit and two-digit decoding choices, preserve both rolling dependencies, then enumerate witnesses or change the token vocabulary.

Published · 13 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Add parse counts only for valid final tokens

Explain the mechanism, why it works, when it fails, and one alternative.

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.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

At each digit, add one-back decodings for a valid single digit and two-back decodings for a valid 10..26 pair.

Problem trace

Add disjoint parse groups only when their final token is valid

Add disjoint parse groups only when their final token is validCount parses by their final valid token. For 226, two parses end in 6 and one ends in 26. Removing that final token leaves an already-counted shorter prefix. The groups are disjoint, so add their counts. Invalid final tokens contribute nothing. Preserve both preceding prefix counts; the empty prefix supplies one way to start.Input 226: group parses by theirfinal tokenFinal 6: inherit 2 parses of prefix22226226Final 26: inherit 1 parse of prefix 2226Disjoint final-token choices: two andone213Remove the final token to reveal itssmaller prefix.Separate validity checksKeep digit order intact when checkingthe range ten through twenty-six10✓Ten is an allowed two-digit code.01xLeading zero: zero-one is not ten.27xTwenty-seven exceeds the allowedrange.
Read it this way: Count parses by their final valid token. For 226, two parses end in 6 and one ends in 26. Removing that final token leaves an already-counted shorter prefix. The groups are disjoint, so add their counts. Invalid final tokens contribute nothing. Preserve both preceding prefix counts; the empty prefix supplies one way to start. Why is ten accepted while zero-one is not, even though both contain a zero?
Full interview answer 13 min read

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.

PrefixValid final-token contributionsCount
2one initial token1
21single 1, pair 212
210pair 10 only1
2101single 1; pair 01 invalid1

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

Input and goalCount ways to decode digits where `1` through `26` map to letters.
Initialize after the leading 2Seed one empty-prefix parse and one parse for initial digit 2.
201
index 020110213
prefix"2"statetwo_back = 1; one_back = 1
index 0
0
prefix
"2"
state
two_back = 1; one_back = 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.
Seed one empty-prefix parse and one parse for initial digit 2. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does 10 contribute a parse while 01 contributes none?
Reference drawing

Problem trace

Add disjoint parse groups only when their final token is valid

Add disjoint parse groups only when their final token is validCount parses by their final valid token. For 226, two parses end in 6 and one ends in 26. Removing that final token leaves an already-counted shorter prefix. The groups are disjoint, so add their counts. Invalid final tokens contribute nothing. Preserve both preceding prefix counts; the empty prefix supplies one way to start.Input 226: group parses by theirfinal tokenFinal 6: inherit 2 parses of prefix22226226Final 26: inherit 1 parse of prefix 2226Disjoint final-token choices: two andone213Remove the final token to reveal itssmaller prefix.Separate validity checksKeep digit order intact when checkingthe range ten through twenty-six10✓Ten is an allowed two-digit code.01xLeading zero: zero-one is not ten.27xTwenty-seven exceeds the allowedrange.
Execution trace
Input and goalCount ways to decode digits where `1` through `26` map to letters.
Initialize after the leading 2Seed one empty-prefix parse and one parse for initial digit 2.
201
index 020110213
prefix"2"statetwo_back = 1; one_back = 1
index 0
0
prefix
"2"
state
two_back = 1; one_back = 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.
Seed one empty-prefix parse and one parse for initial digit 2. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does 10 contribute a parse while 01 contributes none?
Read it this way: Count parses by their final valid token. For 226, two parses end in 6 and one ends in 26. Removing that final token leaves an already-counted shorter prefix. The groups are disjoint, so add their counts. Invalid final tokens contribute nothing. Preserve both preceding prefix counts; the empty prefix supplies one way to start. Why is ten accepted while zero-one is not, even though both contain a zero?

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.