Decode Ways – Solution & Complexity
Watch: Decode Ways with a ways[i] table
226 decodes 3 ways: BBF, BZ and VF. The tempting shortcut says any two digits up to 26 can join, so 206 should be 3 too, but no letter is 0 or starts with 0: only 20, 6 (TF) works. Count with dp instead. ways[i] is the number of ways to read the first i digits, with ways[0] = 1. If digit i is 1 to 9, add ways[i-1]; if the last two digits are 10 to 26, add ways[i-2]. 226 gives 1, 1, 2, 3 and 206 gives 1, 1, 1, 1. Only the last two values matter: O(n) time, O(1) space.
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
Part of Blind 75 · NeetCode 150