Letters are encoded as 1 = A through 26 = Z. Given a digit string, return how many ways it can be decoded.
Before you code
The last letter used either one digit or two. Count both possibilities, but only when they are valid: 0 alone is not a letter, and two digits must form 10 to 26.
Hints
- dp[0] = 1 (the empty prefix).
- If
s[i-1]is 1–9, add dp[i-1]. Ifs[i-2:i]is 10–26, add dp[i-2]. - A string starting with 0 has no decodings.
Production & complexity notes
When solving Decode ways on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in One-dimensional problems to reinforce the underlying pattern.
What it practices
Counting ways by the last step, from One-dimensional problems.