Introduction
The Decode Ways problem is one of the most important String Dynamic Programming interview questions.
Mapping:
1 -> A2 -> B
3 -> C
...
26 -> Z
Goal:
Find the number of ways to decode the string.Example
s = "226"Output = 3Possible Decodings:
2 2 6 = BBF22 6 = VF
2 26 = BZAnswer:
3 Constraints
1 <= s.length <= 100Key Observation
At every position:
Choice 1
Take one digit:
2 → BChoice 2
Take two digits:
22 → VTherefore:
dp[i] = dp[i+1] + dp[i+2]when both choices are valid.
Approach : Dynamic Programming
Explanation
For each index:
- Decode one digit.
- Decode two digits.
- Add valid possibilities.
- Store result.
Dry Run
Input:
s = "226" Start from right:
dp[3] = 1dp[2] = 1
dp[1] = dp[2] + dp[3] = 2 dp[0] = dp[1] + dp[2] = 3
Answer:
3Practice