{"id":"decode-ways","title":"Decode Ways","difficulty":"medium","patterns":["dp-1d"],"primaryConcept":"dp-1d-segmentation","concepts":["dp-1d-segmentation"],"problemForm":"core","companies":[],"category":"dynamic-programming","compareMode":"exact","syntheticTestConfig":{"inputShape":"string","primaryParam":"s","sizeMetric":"length"},"description":"A message containing digits can be decoded by mapping `1` to `A`, `2` to `B`, and so on through `26` to `Z`.\n\nGiven a digit string `s`, return the number of ways to decode the entire string. A decoding cannot use a segment with a leading zero, so `06` is invalid while `10` and `20` are valid.","examples":[{"input":"s = \"12\"","output":"2","explanation":"\"12\" can be decoded as \"AB\" or \"L\"."},{"input":"s = \"226\"","output":"3","explanation":"\"226\" can be decoded as \"BBF\", \"BZ\", or \"VF\"."},{"input":"s = \"06\"","output":"0","explanation":"The leading zero cannot be decoded."}],"constraints":[{"id":"1-len-s-100","text":"1 <= len(s) <= 100","check":{"kind":"sizeRange","target":"s","measure":"stringLength","min":1,"max":100}},{"id":"s-contains-only-digits","text":"s contains only digits","check":{"kind":"domain","target":"s","selector":"stringChars","allowed":["0","1","2","3","4","5","6","7","8","9"]}},{"id":"the-answer-fits-in-a-32-bit-signed-integer","text":"The answer fits in a 32-bit signed integer","check":{"kind":"guarantee","guarantee":"resultRange","min":-2147483648,"max":2147483647}}],"starterCode":"class Solution:\n    def numDecodings(self, s: str) -> int:\n        # Your code here\n        pass","functionName":"numDecodings","testCases":[{"id":"1","input":{"s":"12"},"expected":2,"description":"Two single-or-pair decodings."},{"id":"2","input":{"s":"226"},"expected":3,"description":"Multiple pair choices."},{"id":"3","input":{"s":"06"},"expected":0,"description":"Leading zero is invalid."},{"id":"4","input":{"s":"10"},"expected":1,"description":"Zero can only be paired with a valid previous digit."},{"id":"5","input":{"s":"11106"},"expected":2,"description":"Internal zero blocks some segmentations."},{"id":"6","input":{"s":"2101"},"expected":1,"description":"Only one segmentation survives the zero rules."},{"id":"h1","input":{"s":"27"},"expected":1,"description":"A two-digit number above 26 cannot be paired."},{"id":"h2","input":{"s":"101"},"expected":1,"description":"A zero must be paired, and the trailing digit stands alone."},{"id":"h3","input":{"s":"1001"},"expected":0,"description":"Zero blocks all full-string decodings."},{"id":"h4","input":{"s":"111111"},"expected":13,"description":"A long run of ones follows the Fibonacci-style growth."},{"id":"topup-1","input":{"s":"2611055971756562"},"expected":4,"description":"Top-up case 1: a longer string mixes valid pairs, invalid pairs above 26, and zero handling."},{"id":"topup-2","input":{"s":"230"},"expected":0,"description":"Top-up case 2: the trailing zero cannot pair with 3, so every decoding is blocked."},{"id":"long-run-of-ones","input":{"s":"11111111111111111111111111111111111111111111"},"expected":1134903170,"description":"Forty-four ones give 1134903170 decodings, which still fits in a 32-bit signed integer and is returned as is."}],"hints":[{"level":1,"content":"For each prefix ending at index i, consider whether the last one digit or last two digits can form a valid letter.","revealPattern":false},{"level":2,"content":"Let `dp[i]` count decodings for the first `i` characters. Valid one-digit choices add `dp[i - 1]`, and valid two-digit choices add `dp[i - 2]`.","revealPattern":true},{"level":3,"content":"Initialize `dp[0] = 1` as the empty prefix and set `dp[1] = 1` only after rejecting a leading zero.","revealPattern":true}],"guidedFlow":{"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"plain-recursion","name":"Plain recursion","summary":"Try every one-digit and two-digit split recursively.","decisionReason":"It re-decodes the same suffixes down every branch, so the work grows exponentially.","complexity":{"time":"O(2^n)","space":"O(n)"},"tradeoffs":["Runs in O(2^n) time and uses O(n) space."],"isOptimal":false},{"id":"prefix-dp","name":"Prefix DP table","summary":"Build counts for prefixes from left to right using the previous one or two states.","decisionReason":"Each prefix's count is the ways ending in one valid digit plus the ways ending in a valid two-digit pair, so one left-to-right pass fills it.","complexity":{"time":"O(n)","space":"O(n)"},"tradeoffs":["Runs in O(n) time and uses O(n) space."],"isOptimal":true},{"id":"rolling-dp","name":"Rolling two-state DP","summary":"Keep only the previous two prefix counts.","decisionReason":"Two rolling counts produce the same number of decodings in O(n) time. The guided implementation keeps one slot per prefix so the one-digit and two-digit contributions remain visible together.","complexity":{"time":"O(n)","space":"O(1)"},"tradeoffs":["Runs in O(n) time and uses O(1) space."],"isViable":true,"isOptimal":false}]},"codingCheckpoints":[{"id":"reject-leading-zero","title":"Reject invalid starts","description":"Return 0 before building the DP table when the string is empty or starts with 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"rejects_invalid_prefix","scope":"leading-zero-guard","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Reject inputs that cannot produce any decoding before setting up prefix counts.","doneWhen":"An early guard returns 0 for an empty string or a string whose first character is 0.","shouldFailWhen":"The code can continue into the DP table for an empty input or a leading-zero input.","roles":["input string","invalid first character"],"mustProve":["pre-DP short-circuit return","leading-zero input check"],"mustNotAccept":["checking a non-input string","returning a nonzero count for an invalid start"],"proofSnippets":[{"id":"py-reject-leading-zero","language":"python","code":"class Solution:\n    def numDecodings(self, s: str) -> int:\n        if not s or s[0] == '0':\n            return 0"}]},"commonMistakes":["Letting a leading zero enter the DP recurrence","Returning 1 for an empty or leading-zero string"],"hint":"A string that starts with 0 has no valid first letter."},{"id":"seed-prefix-counts","title":"Seed the prefix counts","description":"Create a dp array of length n + 1 and set dp[0] and dp[1] to 1 for the empty and first valid prefixes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_indexed_base_case","scope":"set-prefix-base-cases","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Seed indexed prefix-count states before scanning longer prefixes.","doneWhen":"The DP table is allocated with room for the empty prefix and both initial prefix counts are written to 1.","shouldFailWhen":"The recurrence reads prefix states before the base cases are seeded.","roles":["indexed DP state","empty prefix base case","first character base case"],"mustProve":["indexed state initialization","indexed base-case write"],"mustNotAccept":["unseeded prefix recurrence"],"proofSnippets":[{"id":"py-seed-prefix-counts","language":"python","code":"class Solution:\n    def numDecodings(self, s: str) -> int:\n        if not s or s[0] == '0':\n            return 0\n        n = len(s)\n        dp = [0] * (n + 1)\n        dp[0] = 1\n        dp[1] = 1"}]},"commonMistakes":["Forgetting the empty-prefix base case","Starting the table at index 0 without room for dp[i - 2]"],"hint":"dp[0] represents one way to decode the empty prefix."},{"id":"scan-prefixes","title":"Scan prefixes from length two","description":"Loop from i = 2 through n so every prefix length is evaluated once.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Scan each prefix length whose decode count depends on earlier prefix counts.","doneWhen":"A loop traverses prefix indices from the first recurrent prefix through the full string.","shouldFailWhen":"The code seeds base cases but never iterates across prefix states.","roles":["prefix index","indexed DP state"],"mustProve":["indexed state-space scan"],"mustNotAccept":["base cases without recurrence scan"],"proofSnippets":[{"id":"py-scan-prefixes","language":"python","code":"class Solution:\n    def numDecodings(self, s: str) -> int:\n        if not s or s[0] == '0':\n            return 0\n        n = len(s)\n        dp = [0] * (n + 1)\n        dp[0] = 1\n        dp[1] = 1\n        for i in range(2, n + 1):\n            pass"}]},"commonMistakes":["Skipping the final prefix","Starting before dp[i - 2] is meaningful"],"hint":"Each iteration should compute the count for one prefix length."},{"id":"compute-prefix-count","title":"Compute the prefix count","description":"For each prefix length, combine the valid one-digit and two-digit predecessor counts and write dp[i].","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-guarded-prefix-count","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"compute-guarded-prefix-count","readMode":"dp-value-query-v1"}]}]},"semanticSpec":{"intent":"Compute each prefix count from valid one-digit and two-digit predecessor states and write it to the indexed DP table.","doneWhen":"The loop accumulates valid predecessor counts and stores the resulting count in dp[i].","shouldFailWhen":"The code checks digit validity but does not write the combined count back to the DP state.","roles":["current prefix state","one-digit predecessor","two-digit predecessor"],"mustProve":["recurrence transition computation","recurrence state writeback"],"mustNotAccept":["validity checks without DP write"],"proofSnippets":[{"id":"py-compute-prefix-count","language":"python","code":"def numDecodings(s):\n    if not s or s[0] == '0':\n        return 0\n    n = len(s)\n    dp = [0] * (n + 1)\n    dp[0] = 1\n    dp[1] = 1\n    for i in range(2, n + 1):\n        count = 0\n        if s[i - 1] != '0':\n            count += dp[i - 1]\n        two_digit = int(s[i - 2:i])\n        if 10 <= two_digit <= 26:\n            count += dp[i - 2]\n        dp[i] = count"}]},"commonMistakes":["Allowing standalone zero","Accepting two-digit values outside 10 through 26","Computing a count but never storing it in dp[i]"],"hint":"Both valid segment choices contribute to the same dp[i] state."},{"id":"return-final-count","title":"Return the full-string count","description":"Return dp[n], the count for the entire string.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the indexed terminal prefix count after the recurrence scan.","doneWhen":"The function returns the DP state for the full string length.","shouldFailWhen":"The function returns an intermediate prefix, a boolean validity flag, or the DP array.","roles":["terminal indexed DP state","full prefix index"],"mustProve":["indexed terminal state return"],"mustNotAccept":["non-terminal prefix return"],"proofSnippets":[{"id":"py-return-final-count","language":"python","code":"def numDecodings(s):\n    if not s or s[0] == '0':\n        return 0\n    n = len(s)\n    dp = [0] * (n + 1)\n    dp[0] = 1\n    dp[1] = 1\n    for i in range(2, n + 1):\n        count = 0\n        if s[i - 1] != '0':\n            count += dp[i - 1]\n        two_digit = int(s[i - 2:i])\n        if 10 <= two_digit <= 26:\n            count += dp[i - 2]\n        dp[i] = count\n    return dp[n]"}]},"commonMistakes":["Returning dp[n - 1]","Returning a boolean valid-or-invalid result","Applying an unnecessary modulo"],"hint":"The last DP cell stores the answer for the full prefix."}],"version":2,"slides":[{"id":"read-the-signal","kind":"info","chapter":"The message","eyebrow":"Read the problem","title":"How many ways to read the digits","workspacePanel":"problem","body":["Digits map to letters: 1 is A, 2 is B, on up to 26 is Z. Given a string of digits, count how many different letter strings it could decode to.","\"12\" reads as \"AB\" (1, 2) or \"L\" (12), so 2 ways. A 0 maps to no letter, so it can only ever appear inside 10 or 20."]},{"id":"brute","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Branch on every cut","workspacePanel":"trace","body":["The direct approach starts at the front and tries both cuts: take the next one digit as a letter, or take the next two digits as a letter, then recurse on whatever remains.","Each call splits into two, and those split again, all the way down the string."],"codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def numDecodings(s: str) -> int:\n    n = len(s)\n    def count(start: int) -> int:\n        if start == n:\n            return 1\n        total = 0\n        if s[start] != '0':\n            total += count(start + 1)\n        if start + 1 < n and 10 <= int(s[start:start + 2]) <= 26:\n            total += count(start + 2)\n        return total\n    return count(0)","steps":[{"id":"take-one","title":"From index 1, take \"2\" alone and recurse on \"26\"","codeLine":7,"summary":"The single-digit branch advances one position.","state":{"rows":[{"label":"s","values":["1","2","2","6"]}],"i":1}},{"id":"take-two","title":"From index 1, take \"22\" together and recurse on \"6\"","codeLine":9,"summary":"The two-digit branch advances two positions, from the same starting point.","state":{"rows":[{"label":"s","values":["1","2","2","6"]}],"i":1}},{"id":"land-on-6","title":"Both branches end up calling count on the trailing \"6\"","codeLine":10,"summary":"Take \"2\" then \"2\", or take \"22\": either path lands on the same remaining \"6\".","state":{"rows":[{"label":"s","values":["1","2","2","6"]}],"i":3}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const n = s.length;\nfunction count(start) {\n    if (start === n) {\n        return 1;\n    }\n    let total = 0;\n    if (s[start] !== \"0\") {\n        total += count((start + 1));\n    }\n    if ((start + 1) < n && 10 <= Number.parseInt(s.slice(start, (start + 2)), 10) && Number.parseInt(s.slice(start, (start + 2)), 10) <= 26) {\n        total += count((start + 2));\n    }\n    return total;\n}\nreturn count(0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":15},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"11":{"startLine":13,"endLine":14}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const n = s.length;\nfunction count(start: number): number {\n    if (start === n) {\n        return 1;\n    }\n    let total = 0;\n    if (s[start] !== \"0\") {\n        total += count((start + 1));\n    }\n    if ((start + 1) < n && 10 <= Number.parseInt(s.slice(start, (start + 2)), 10) && Number.parseInt(s.slice(start, (start + 2)), 10) <= 26) {\n        total += count((start + 2));\n    }\n    return total;\n}\nreturn count(0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":15},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"11":{"startLine":13,"endLine":14}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int n = s.Length;\nint Count(int start) {\n    if (start == n) {\n        return 1;\n    }\n    int total = 0;\n    if (s[start] != '0') {\n        total += Count(start + 1);\n    }\n    if (start + 1 < n && 10 <= int.Parse(s.Substring(start, (start + 2) - (start))) && int.Parse(s.Substring(start, (start + 2) - (start))) <= 26) {\n        total += Count(start + 2);\n    }\n    return total;\n    return 0;\n}\nreturn Count(0);","lineMap":{"2":1,"4":3,"5":4,"6":6,"7":7,"8":8,"9":10,"10":11,"11":13,"12":16},"statementBundles":{"2":{"startLine":1,"endLine":2},"5":{"startLine":4,"endLine":5},"8":{"startLine":8,"endLine":9},"10":{"startLine":11,"endLine":12},"11":{"startLine":13,"endLine":15}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"function<int(int)> count;\n\nint n = s.size();\ncount = [&]( int start ) -> int {\n    if (start == n) {\n        return 1;\n    }\n    int total = 0;\n    if (s[start] != '0') {\n        total += count((start + 1));\n    }\n    if (((start + 1) < n && (10 <= stoi(string(s.begin() + start, s.begin() + (start + 2))) && stoi(string(s.begin() + start, s.begin() + (start + 2))) <= 26))) {\n        total += count((start + 2));\n    }\n    return total;\n};\nreturn count(0);","lineMap":{"2":3,"4":5,"5":6,"6":8,"7":9,"8":10,"9":12,"10":13,"11":15,"12":17},"statementBundles":{"2":{"startLine":3,"endLine":4},"5":{"startLine":6,"endLine":7},"8":{"startLine":10,"endLine":11},"10":{"startLine":13,"endLine":14},"11":{"startLine":15,"endLine":16}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"private static int count(int start, int n, String s) {\n    if (start == n) {\n        return 1;\n    }\n    int total = 0;\n    if (s.charAt(start) != '0') {\n        total += count((start + 1), n, s);\n    }\n    if (((start + 1) < n && (10 <= Integer.parseInt(s.substring(start, (start + 2))) && Integer.parseInt(s.substring(start, (start + 2))) <= 26))) {\n        total += count((start + 2), n, s);\n    }\n    return total;\n}\n\nint n = s.length();\nreturn count(0, n, s);","lineMap":{"2":15,"4":2,"5":3,"6":5,"7":6,"8":7,"9":9,"10":10,"11":12,"12":16},"statementBundles":{"5":{"startLine":3,"endLine":4},"8":{"startLine":7,"endLine":8},"10":{"startLine":10,"endLine":11},"11":{"startLine":12,"endLine":13}}}}}},{"id":"brute-cost","kind":"case-probe","chapter":"The obvious way","eyebrow":"Feel the cost","title":"Across a long run of digits, how fast does the call count grow?","workspacePanel":"trace","summary":"Every call that has two legal cuts spawns two more calls.","options":[{"id":"exp","label":"It roughly doubles with each added digit","rationale":"Two legal cuts at most positions means each call spawns two more, so the call tree branches exponentially down the string.","isCorrect":true},{"id":"linear","label":"One call per digit","rationale":"A single call already makes up to two recursive calls, so the total is far more than one per position."},{"id":"squared","label":"About length squared","rationale":"The branching doubles across long runs of legal cuts, so the growth outruns any polynomial in the length."}],"answer":"It roughly doubles per added digit. Each call branches into two, so the call tree is exponential, even though the string itself is short.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cost-state","state":{"rows":[{"label":"s","values":["1","1","1","1","1","1"]}],"i":0}}]}},{"id":"repeated-work","kind":"case-probe","chapter":"The obvious way","eyebrow":"Name the waste","title":"What does the exponential blow-up keep recomputing?","workspacePanel":"trace","summary":"Take \"2\" then \"2\", or take \"22\": both land on count(3), the trailing \"6\".","options":[{"id":"suffix","label":"The number of ways to decode the same remaining suffix","rationale":"How a suffix decodes does not depend on what came before it, so that count recurs across branches and can be computed once.","isCorrect":true},{"id":"read","label":"Reading the digits","rationale":"Reading a digit is cheap; the repeated cost is re-counting decodings of suffixes that recur."},{"id":"map","label":"Mapping digits to letters","rationale":"The letter mapping is never actually needed, only the count; the waste is re-counting shared suffixes."}],"answer":"The suffix counts. A suffix decodes the same way regardless of the prefix before it, so caching the count per position removes the repetition.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"repeated-work-state","state":{"rows":[{"label":"s","values":["1","2","2","6"]}],"i":3}}]}},{"id":"two-choices","kind":"case-probe","chapter":"The idea","eyebrow":"Find the cases","title":"Look at the newest digit. The decoding ending here ends in what?","workspacePanel":"visualizer","summary":"Call the count for the first i digits dp[i].","options":[{"id":"one-or-two","label":"A single digit on its own, or a two-digit pair with the digit before it","rationale":"The final letter came from exactly one digit (1 through 9) or from two digits read together (10 through 26); there is no third way.","isCorrect":true},{"id":"any","label":"Any number of trailing digits","rationale":"No letter maps past 26, so a chunk is at most two digits long."},{"id":"one-only","label":"Always a single digit","rationale":"Two-digit letters like 12 = \"L\" exist, so a pair is a real second option."}],"answer":"A single digit, or a two-digit pair with the previous digit. Those are the only two ways the last letter could have been formed.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"cases-state","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,0,0,0]}],"i":2}}]}},{"id":"add-the-ways","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"If both the single and the pair are valid, how do the counts combine?","workspacePanel":"visualizer","summary":"The last letter is either the lone digit, or the two-digit pair.","options":[{"id":"add","label":"Add them: dp[i-1] for the single plus dp[i-2] for the pair","rationale":"Every decoding ending in the lone digit extends one of dp[i-1], and every decoding ending in the pair extends one of dp[i-2], and the two sets do not overlap.","isCorrect":true},{"id":"mult","label":"Multiply them","rationale":"The single and the pair are alternative endings from disjoint sets, so the counts add."},{"id":"max","label":"Take the larger","rationale":"Both endings produce valid decodings, so all of them count; you add rather than pick one."}],"answer":"Add them. The lone-digit decodings (dp[i-1]) and the pair decodings (dp[i-2]) are disjoint, so dp[i] is their sum, just like the two ways to reach a stair.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"add-state","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,2,0,0],"changed":[2]}],"i":2}}]}},{"id":"validity","kind":"case-probe","chapter":"The idea","eyebrow":"Guard the options","title":"When is each option invalid?","workspacePanel":"visualizer","summary":"Try cuts like a lone 0 and the pair 32.","options":[{"id":"rules","label":"The single is invalid if the digit is 0; the pair is invalid unless it is 10 to 26","rationale":"No letter maps to 0, so a lone 0 contributes nothing, and only 10 through 26 are valid two-letter chunks.","isCorrect":true},{"id":"never","label":"Both are always allowed","rationale":"\"0\" maps to no letter and \"27\" is past Z, so each option needs a validity check."},{"id":"single-only","label":"Only the single digit can be invalid","rationale":"Pairs like 27 or 00 are also invalid; the pair needs the 10-to-26 range check too."}],"answer":"A lone 0 is invalid (no letter), and a pair counts only if it falls in 10 to 26. An invalid option simply contributes 0 to the sum.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"validity-state","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,2,0,0]}],"i":2}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,0,0,0]}],"i":1}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"The empty prefix and first digit are seeded","workspacePanel":"visualizer","body":["dp[0] is 1: the empty string decodes one way, as nothing. dp[1] is 1 too, since a single non-zero digit reads exactly one way.","Tracing \"1226\", each later position adds the ways ending in its single digit and the ways ending in its valid pair."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,0,0,0]}],"i":1}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Fill the counts","title":"Count the decodings of \"1226\"","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"pos-2","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,2,0,0],"changed":[2]}],"i":2}},{"id":"pos-3","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,2,3,0],"changed":[3]}],"i":3}},{"id":"pos-4","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,2,3,5],"changed":[4]}],"i":4}}]},"beats":[{"id":"pos-2","title":"Position 2, digit \"2\" after \"1\". What is dp[2]?","prompt":"Both look-backs are on the panel; decide which are legal here, then total them.","options":[{"id":"two","label":"2 = dp[1] + dp[0]","rationale":"Lone \"2\" is valid, so add dp[1] = 1; pair \"12\" is 12, in range, so add dp[0] = 1, giving 2.","isCorrect":true},{"id":"one","label":"1, the single only","rationale":"\"12\" is a valid pair (it is 12, within 10 to 26), so its dp[0] count is added too."},{"id":"mult","label":"1, the counts multiply","rationale":"The single and pair endings are alternatives, so their counts add, giving 2."}],"answer":"2. Lone \"2\" adds dp[1] = 1, and pair \"12\" (valid) adds dp[0] = 1, so dp[2] = 2."},{"id":"pos-3","title":"Position 3, digit \"2\" after \"2\". What is dp[3]?","prompt":"Read the look-back counts off the table and total the legal ones.","options":[{"id":"three","label":"3 = dp[2] + dp[1]","rationale":"Lone \"2\" adds dp[2] = 2, and pair \"22\" (22, in range) adds dp[1] = 1, so 2 + 1 = 3.","isCorrect":true},{"id":"two","label":"2, the single only","rationale":"\"22\" is 22, a valid pair, so dp[1] = 1 is added as well, giving 3."},{"id":"four","label":"4, dp[2] + dp[2]","rationale":"The pair looks back two positions to dp[1], so the sum is 2 + 1 = 3."}],"answer":"3. Lone \"2\" adds dp[2] = 2, and pair \"22\" (valid) adds dp[1] = 1, so dp[3] = 3."},{"id":"pos-4","title":"Position 4, digit \"6\" after \"2\". The answer?","prompt":"Check whether \"26\" still falls in range, then total the legal look-backs.","options":[{"id":"five","label":"5 = dp[3] + dp[2]","rationale":"Lone \"6\" adds dp[3] = 3, and pair \"26\" (exactly 26, still in range) adds dp[2] = 2, so 3 + 2 = 5.","isCorrect":true},{"id":"three","label":"3, the single only","rationale":"26 is the largest valid pair, so \"26\" counts; its dp[2] = 2 is added, giving 5."},{"id":"six","label":"6, all the smaller counts","rationale":"Only the two look-backs dp[3] and dp[2] contribute, so the total is 3 + 2 = 5."}],"answer":"5. Lone \"6\" adds dp[3] = 3, and pair \"26\" (26, the boundary, valid) adds dp[2] = 2, so the answer is 5."}]},{"id":"pair-range-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Could every adjacent pair just count as a letter?","summary":"A broken version treats the two-digit pair like the single-digit branch and always adds dp[i-2] when a previous digit exists. Watch that shortcut decode \"27\".","pitfall":"The code below adds dp[i-2] for any two-digit pair, without checking it lands in 10 to 26.","whyItMatters":"\"27\" has exactly one decoding, \"2\" then \"7\", because 27 is past Z and maps to no letter. The unguarded pair branch added dp[0] for \"27\" anyway and reported 2. The 10-to-26 range check is what rejects pairs above 26, along with the 00 and 0x pairs that map to nothing.","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"def numDecodings(s: str) -> int:\n    if not s or s[0] == '0':\n        return 0\n    n = len(s)\n    dp: list[int] = [0] * (n + 1)\n    dp[0] = dp[1] = 1\n    for i in range(2, n + 1):\n        count = 0\n        if s[i - 1] != '0':\n            count += dp[i - 1]\n        count += dp[i - 2]\n        dp[i] = count\n    return dp[n]","steps":[{"id":"single","title":"\"7\" alone is valid: add dp[1]","codeLine":10,"summary":"The single-digit branch is fine; the running count is 1.","state":{"rows":[{"label":"s","values":["·","2","7"]},{"label":"dp","values":[1,1,1],"changed":[2]}],"i":2}},{"id":"bad-pair","title":"\"27\" is added as a pair, with no range check","codeLine":11,"summary":"The line adds dp[0] for the pair unconditionally, pushing the count to 2.","state":{"rows":[{"label":"s","values":["·","2","7"]},{"label":"dp","values":[1,1,2],"changed":[2]}],"i":2}},{"id":"wrong","title":"It returns 2, but \"27\" decodes only one way","codeLine":12,"summary":"The only decoding is \"2\" then \"7\"; the missing 10-to-26 guard let an invalid pair through.","state":{"rows":[{"label":"s","values":["·","2","7"]},{"label":"dp","values":[1,1,2],"changed":[2]}],"i":2}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"if (s.length === 0 || s[0] === \"0\") {\n    return 0;\n}\nconst n = s.length;\nconst dp = Array((n + 1)).fill(0);\nconst value = 1;\ndp[0] = value;\ndp[1] = value;\nfor (let i = 2; i < (n + 1); i++) {\n    let count = 0;\n    if (s[(i - 1)] !== \"0\") {\n        count += dp[(i - 1)];\n    }\n    count += dp[(i - 2)];\n    dp[i] = count;\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":14,"12":15,"13":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":8},"10":{"startLine":12,"endLine":13},"12":{"startLine":15,"endLine":16}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"if (s.length === 0 || s[0] === \"0\") {\n    return 0;\n}\nconst n = s.length;\nconst dp = Array((n + 1)).fill(0);\nconst value = 1;\ndp[0] = value;\ndp[1] = value;\nfor (let i = 2; i < (n + 1); i++) {\n    let count = 0;\n    if (s[(i - 1)] !== \"0\") {\n        count += dp[(i - 1)];\n    }\n    count += dp[(i - 2)];\n    dp[i] = count;\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":14,"12":15,"13":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":8},"10":{"startLine":12,"endLine":13},"12":{"startLine":15,"endLine":16}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"if ((s.isEmpty() || s.charAt(0) == '0')) {\n    return 0;\n}\nint n = s.length();\nint[] dp = new int[(n + 1)];\nint value = 1;\ndp[0] = value;\ndp[1] = value;\nfor (int i = 2; i < (n + 1); i++) {\n    int count = 0;\n    if (s.charAt(i - 1) != '0') {\n        count += dp[(i - 1)];\n    }\n    count += dp[(i - 2)];\n    dp[i] = count;\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":14,"12":15,"13":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":8},"10":{"startLine":12,"endLine":13},"12":{"startLine":15,"endLine":16}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"if (s.Length == 0 || s[0] == '0') {\n    return 0;\n}\nint n = s.Length;\nList<int> dp = Enumerable.Repeat<int>(0, n + 1).ToList();\nint value = 1;\ndp[0] = value;\ndp[1] = value;\nfor (int i = 2; i < n + 1; i++) {\n    int count = 0;\n    if (s[i - 1] != '0') {\n        count += dp[i - 1];\n    }\n    count += dp[i - 2];\n    dp[i] = count;\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":14,"12":15,"13":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":8},"10":{"startLine":12,"endLine":13},"12":{"startLine":15,"endLine":16}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"if ((s.empty() || s[0] == '0')) {\n    return 0;\n}\nint n = s.size();\nvector<int> dp = vector<int>((n + 1), 0);\nint value = 1;\ndp[0] = value;\ndp[1] = value;\nfor (int i = 2; i < (n + 1); i++) {\n    int count = 0;\n    if (s[(i - 1)] != '0') {\n        count += dp[(i - 1)];\n    }\n    count += dp[(i - 2)];\n    dp[i] = count;\n}\nreturn dp[n];","lineMap":{"2":1,"3":2,"4":4,"5":5,"6":6,"7":9,"8":10,"9":11,"10":12,"11":14,"12":15,"13":17},"statementBundles":{"3":{"startLine":2,"endLine":3},"6":{"startLine":6,"endLine":8},"10":{"startLine":12,"endLine":13},"12":{"startLine":15,"endLine":16}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Adding the single-digit and valid-pair counts at each position let the table build the total decodings in one sweep.","Now hunt for the breaks that zeros cause. What happens when the string starts with a 0, and what about a 0 that no neighboring digit can pair into a valid letter?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,0,0,0]}],"i":1}}]}},{"id":"leading-zero-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"When the string starts with 0, how many ways?","workspacePanel":"visualizer","summary":"s = \"06\".","options":[{"id":"zero","label":"0, it cannot be decoded","rationale":"No letter maps to 0, and valid pairs start at 10, so the very first digit already kills every decoding.","isCorrect":true},{"id":"one","label":"1, read it as 6","rationale":"The leading 0 still has to be decoded and maps to no letter, so the whole string fails."},{"id":"two","label":"2, 0 then 6 or 06","rationale":"0 maps to no letter and 06 is below the valid pair range, so neither reading works."}],"answer":"0. A leading 0 maps to no letter and 06 falls below 10, so there is no valid decoding.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"leading-state","state":{"rows":[{"label":"s","values":["·","0","6"]},{"label":"dp","values":[1,0,0]}],"i":1}}]}},{"id":"embedded-zero-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"A 0 that no pair can absorb. How many ways?","workspacePanel":"visualizer","summary":"s = \"30\".","options":[{"id":"zero","label":"0, the 0 is stranded","rationale":"The 0 cannot stand alone, and \"30\" is past 26, so nothing can absorb the 0 and the string fails.","isCorrect":true},{"id":"one","label":"1, read as 30","rationale":"30 is above 26, so it is not a valid letter; the 0 has no legal home."},{"id":"two","label":"2, 3 then 0 or 30","rationale":"Neither \"0\" alone nor \"30\" as a pair is valid, so both readings fail."}],"answer":"0. The 0 cannot be a single letter, and \"30\" is outside 10 to 26, so it can never be decoded.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"embedded-state","state":{"rows":[{"label":"s","values":["·","3","0"]},{"label":"dp","values":[1,1,0],"changed":[2]}],"i":2}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Turn the rule into code","workspacePanel":"visualizer","summary":"The two look-backs only count when the digit, or the pair, forms a real letter.","body":["Walk the string left to right, and at each position count the decodings that end there by reaching back at most two digits: one step back when the current digit stands alone as a letter, two steps back when it joins its predecessor into a single valid letter.","Sum whichever look-backs are legal at that spot, and the count for the full length is the answer."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"rows":[{"label":"s","values":["·","1","2","2","6"]},{"label":"dp","values":[1,1,0,0,0]}],"i":1}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the prefix counts","eyebrow":"Code the rule","summary":"Each prefix's count is its legal look-backs added together. Now build it: seed dp[0] and dp[1] to 1 once the leading zero is ruled out, scan prefixes from length two onward, at each one add dp[i-1] for a valid single digit and dp[i-2] for a pair in 10 to 26, then return dp[n].","workspacePanel":"code","checkpoints":[{"id":"reject-leading-zero","title":"Reject invalid starts","description":"Return 0 before building the DP table when the string is empty or starts with 0.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"rejects_invalid_prefix","scope":"leading-zero-guard","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Reject inputs that cannot produce any decoding before setting up prefix counts.","doneWhen":"An early guard returns 0 for an empty string or a string whose first character is 0.","shouldFailWhen":"The code can continue into the DP table for an empty input or a leading-zero input.","roles":["input string","invalid first character"],"mustProve":["pre-DP short-circuit return","leading-zero input check"],"mustNotAccept":["checking a non-input string","returning a nonzero count for an invalid start"],"proofSnippets":[{"id":"py-reject-leading-zero","language":"python","code":"class Solution:\n    def numDecodings(self, s: str) -> int:\n        if not s or s[0] == '0':\n            return 0"}]},"commonMistakes":["Letting a leading zero enter the DP recurrence","Returning 1 for an empty or leading-zero string"],"hint":"A string that starts with 0 has no valid first letter."},{"id":"seed-prefix-counts","title":"Seed the prefix counts","description":"Create a dp array of length n + 1 and set dp[0] and dp[1] to 1 for the empty and first valid prefixes.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_indexed_base_case","scope":"set-prefix-base-cases","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Seed indexed prefix-count states before scanning longer prefixes.","doneWhen":"The DP table is allocated with room for the empty prefix and both initial prefix counts are written to 1.","shouldFailWhen":"The recurrence reads prefix states before the base cases are seeded.","roles":["indexed DP state","empty prefix base case","first character base case"],"mustProve":["indexed state initialization","indexed base-case write"],"mustNotAccept":["unseeded prefix recurrence"],"proofSnippets":[{"id":"py-seed-prefix-counts","language":"python","code":"class Solution:\n    def numDecodings(self, s: str) -> int:\n        if not s or s[0] == '0':\n            return 0\n        n = len(s)\n        dp = [0] * (n + 1)\n        dp[0] = 1\n        dp[1] = 1"}]},"commonMistakes":["Forgetting the empty-prefix base case","Starting the table at index 0 without room for dp[i - 2]"],"hint":"dp[0] represents one way to decode the empty prefix."},{"id":"scan-prefixes","title":"Scan prefixes from length two","description":"Loop from i = 2 through n so every prefix length is evaluated once.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"scans_indexed_state_space","scope":"outer-loop","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Scan each prefix length whose decode count depends on earlier prefix counts.","doneWhen":"A loop traverses prefix indices from the first recurrent prefix through the full string.","shouldFailWhen":"The code seeds base cases but never iterates across prefix states.","roles":["prefix index","indexed DP state"],"mustProve":["indexed state-space scan"],"mustNotAccept":["base cases without recurrence scan"],"proofSnippets":[{"id":"py-scan-prefixes","language":"python","code":"class Solution:\n    def numDecodings(self, s: str) -> int:\n        if not s or s[0] == '0':\n            return 0\n        n = len(s)\n        dp = [0] * (n + 1)\n        dp[0] = 1\n        dp[1] = 1\n        for i in range(2, n + 1):\n            pass"}]},"commonMistakes":["Skipping the final prefix","Starting before dp[i - 2] is meaningful"],"hint":"Each iteration should compute the count for one prefix length."},{"id":"compute-prefix-count","title":"Compute the prefix count","description":"For each prefix length, combine the valid one-digit and two-digit predecessor counts and write dp[i].","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"computes_recurrence_transition","scope":"compute-guarded-prefix-count","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"writes_recurrence_state","scope":"compute-guarded-prefix-count","readMode":"dp-value-query-v1"}]}]},"semanticSpec":{"intent":"Compute each prefix count from valid one-digit and two-digit predecessor states and write it to the indexed DP table.","doneWhen":"The loop accumulates valid predecessor counts and stores the resulting count in dp[i].","shouldFailWhen":"The code checks digit validity but does not write the combined count back to the DP state.","roles":["current prefix state","one-digit predecessor","two-digit predecessor"],"mustProve":["recurrence transition computation","recurrence state writeback"],"mustNotAccept":["validity checks without DP write"],"proofSnippets":[{"id":"py-compute-prefix-count","language":"python","code":"def numDecodings(s):\n    if not s or s[0] == '0':\n        return 0\n    n = len(s)\n    dp = [0] * (n + 1)\n    dp[0] = 1\n    dp[1] = 1\n    for i in range(2, n + 1):\n        count = 0\n        if s[i - 1] != '0':\n            count += dp[i - 1]\n        two_digit = int(s[i - 2:i])\n        if 10 <= two_digit <= 26:\n            count += dp[i - 2]\n        dp[i] = count"}]},"commonMistakes":["Allowing standalone zero","Accepting two-digit values outside 10 through 26","Computing a count but never storing it in dp[i]"],"hint":"Both valid segment choices contribute to the same dp[i] state."},{"id":"return-final-count","title":"Return the full-string count","description":"Return dp[n], the count for the entire string.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_indexed_terminal_state","scope":"return-result","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Return the indexed terminal prefix count after the recurrence scan.","doneWhen":"The function returns the DP state for the full string length.","shouldFailWhen":"The function returns an intermediate prefix, a boolean validity flag, or the DP array.","roles":["terminal indexed DP state","full prefix index"],"mustProve":["indexed terminal state return"],"mustNotAccept":["non-terminal prefix return"],"proofSnippets":[{"id":"py-return-final-count","language":"python","code":"def numDecodings(s):\n    if not s or s[0] == '0':\n        return 0\n    n = len(s)\n    dp = [0] * (n + 1)\n    dp[0] = 1\n    dp[1] = 1\n    for i in range(2, n + 1):\n        count = 0\n        if s[i - 1] != '0':\n            count += dp[i - 1]\n        two_digit = int(s[i - 2:i])\n        if 10 <= two_digit <= 26:\n            count += dp[i - 2]\n        dp[i] = count\n    return dp[n]"}]},"commonMistakes":["Returning dp[n - 1]","Returning a boolean valid-or-invalid result","Applying an unnecessary modulo"],"hint":"The last DP cell stores the answer for the full prefix."}]},{"id":"complete","kind":"complete","chapter":"Code","title":"What to carry forward","eyebrow":"Take it with you","summary":"Each prefix's count is the ways ending in a valid single digit plus the ways ending in a valid two-digit pair.","workspacePanel":"code","body":["The final letter spans one digit or two, so dp[i] = dp[i-1] + dp[i-2], with each term added only when that chunk is a real letter.","Everything tricky lives in those validity guards: a lone 0 is no letter, and a pair must land in 10 to 26."],"takeaways":[{"title":"One digit or two, so the counts add","body":"dp[i] = (single valid ? dp[i-1] : 0) + (pair valid ? dp[i-2] : 0)."},{"title":"Zeros and 27+ are the traps","body":"A 0 maps to no letter and only survives inside 10 or 20; any pair above 26 contributes nothing."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"},"executionStyle":"solution-method"}
