Decode Ways
Medium
Dynamic ProgrammingString
Problem
A digit string can be decoded into letters where "1"→"A", "2"→"B", …, "26"→"Z". Given a digit-only string s, return the number of ways to decode it. "0" alone cannot decode.
Example 1
Input: s = "12"
Output: 2
Explain: "AB" (1 2) or "L" (12)
Example 2
Input: s = "226"
Output: 3
Example 3
Input: s = "06"
Output: 0
Constraints
- 1 ≤ s.length ≤ 100
- digits only
Approach — Dynamic Programming
This is a Dynamic Programming problem. The idea: break the problem into overlapping subproblems and build the answer up, caching results so nothing is recomputed. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) to O(n²) time.
Solution code
Python
class Solution:
def numDecodings(self, 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 prev1
Java
class Solution {
public int numDecodings(String s) {
int n = s.length();
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = s.charAt(0) == '0' ? 0 : 1;
for (int i = 2; i <= n; i++) {
int one = Integer.parseInt(s.substring(i - 1, i));
int two = Integer.parseInt(s.substring(i - 2, i));
if (one >= 1) dp[i] += dp[i - 1];
if (two >= 10 && two <= 26) dp[i] += dp[i - 2];
}
return dp[n];
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Decode Ways interactively → ← All solutions