Algorithms · Visualized
DP: Decode Ways
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Given a string of digits where 'A'=1, 'B'=2, ..., 'Z'=26, counts how many ways the string can be decoded into letters. Time: O(n) average, O(n) worst; space: O(n), reducible to O(1).
Big-O: The most-asked interview category — 35 classics here.
Decode Ways
Dynamic ProgrammingGiven a string of digits where 'A'=1, 'B'=2, ..., 'Z'=26, counts how many ways the string can be decoded into letters. dp[i] represents the number of ways to decode the first i characters, built from whether the last one or two digits form valid letter codes.
How Decode Ways Works
- Define dp[i] as the number of ways to decode the first i characters of the string. Base case: dp[0] = 1 (empty string has exactly one, trivial, decoding).
- For each position i, check if the single digit at position i-1 is between '1' and '9' (a valid single-letter code) — if so, add dp[i-1] to dp[i].
- Also check if the two digits ending at position i-1 (i.e. positions i-2 and i-1) form a valid two-digit code between '10' and '26' — if so, add dp[i-2] to dp[i].
- Sum both contributions (if valid) to get dp[i] — this accounts for every way of splitting off either a 1-digit or 2-digit letter at this position.
- Return dp[n] (n = length of the string) as the total number of valid decodings.
Decode Ways Worked Example
Input: 226
dp[0]=1. dp[1]: '2' is valid single digit → dp[1]=dp[0]=1. dp[2]: '2' valid single → +dp[1]=1; '22' valid two-digit (≤26) → +dp[0]=1; dp[2]=1+1=2. dp[3]: '6' valid single → +dp[2]=2; '26' valid two-digit → +dp[1]=1; dp[3]=2+1=3. Total decodings: 3 (corresponding to 'BBF', 'BZ', 'VF').
| 0 | 1 | |
|---|---|---|
| dp | 1 | 1 |
def num_decode(s):
if not s or s[0] == '0':
return 0
prev2, prev1 = 1, 1
for i in range(1, len(s)):
cur = 0
if s[i] != '0':
cur += prev1
if 10 <= int(s[i - 1:i + 1]) <= 26:
cur += prev2
prev2, prev1 = prev1, cur
return prev1Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Decode Ways Time & Space Complexity
When to Use Decode Ways
- Decoding schemes in data transmission/encoding systems, and a classic example of DP with 'look back 1 or 2 positions' transitions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.