Decode Ways – Solution & Complexity
Solution Walkthrough
Step 1: Define the suffix state
- The choice at index
ionly affects the remaining suffix after consuming one or two digits. - That makes this a natural dynamic-programming problem over suffixes.
- The choice at index
Step 2: Brute-force baseline
- A recursive search tries one-digit and two-digit decodes whenever they are valid.
- Without memoization, repeated suffixes explode exponentially.
Step 3: Rolling DP transition
- If
s[i]is0, there are0ways from that position. - Otherwise, start with the number of ways from
i + 1(taking one digit). - If
s[i:i+2]is between10and26, also add the number of ways fromi + 2.
- If
Step 4: Final solution (all languages)
A right-to-left scan only needs the next two DP values, so the suffix DP compresses to constant space.
Step 5: Common mistakes and follow-ups
- Treating
0as a standalone letter, which is never allowed. - Allowing any two-digit number under
30; only10through26are valid pairs. - Follow-up: when
*is introduced, the recurrence stays similar but each branch contributes multiple counts instead of just one.
- Treating