76. Decode Ways
Letters are encoded as A → "1", B → "2", …, Z → "26". Given a digit string s, return the number of ways to decode it. A part like "06" is invalid.
Example 1
Input:
s = "12"Output:
2Explanation: “AB” (1 2) or “L” (12).
Example 2
Input:
s = "226"Output:
3Explanation: “BZ”, “VF”, “BBF”.
Hint 1
Like climbing stairs: the last piece is one digit or two digits.
Hint 2
A single digit is valid unless it is 0; a pair is valid if it is 10–26.
Approach 1: Memoised recursion
ways(i) from the end.
⏱ Time O(n)💾 Space O(n)
Approach 2: Rolling DP ✅
Two variables.
⏱ Time O(n)💾 Space O(1)
Reference solution for Rolling DP (time O(n), space O(1)). Each solution passes every test in all four languages.
class Solution:
def numDecodings(self, s: str) -> int:
prev2, prev1 = 1, 1 if s[0] != '0' else 0 # ways for s[:i-2], s[:i-1]
for i in range(1, len(s)):
cur = 0
if s[i] != '0':
cur += prev1 # take one digit
if 10 <= int(s[i - 1:i + 1]) <= 26:
cur += prev2 # take two digits
prev2, prev1 = prev1, cur
return prev1class Solution {
public int numDecodings(String s) {
int prev2 = 1, prev1 = s.charAt(0) != '0' ? 1 : 0;
for (int i = 1; i < s.length(); i++) {
int cur = 0, two = Integer.parseInt(s.substring(i - 1, i + 1));
if (s.charAt(i) != '0') cur += prev1; // one digit
if (two >= 10 && two <= 26) cur += prev2; // two digits
prev2 = prev1; prev1 = cur;
}
return prev1;
}
}class Solution {
public:
int numDecodings(string s) {
int prev2 = 1, prev1 = s[0] != '0' ? 1 : 0;
for (size_t i = 1; i < s.size(); i++) {
int cur = 0, two = (s[i - 1] - '0') * 10 + (s[i] - '0');
if (s[i] != '0') cur += prev1; // one digit
if (two >= 10 && two <= 26) cur += prev2; // two digits
prev2 = prev1; prev1 = cur;
}
return prev1;
}
};function numDecodings(s) {
let prev2 = 1, prev1 = s[0] !== '0' ? 1 : 0;
for (let i = 1; i < s.length; i++) {
let cur = 0;
const two = Number(s.slice(i - 1, i + 1));
if (s[i] !== '0') cur += prev1; // one digit
if (two >= 10 && two <= 26) cur += prev2; // two digits
[prev2, prev1] = [prev1, cur];
}
return prev1;
}Try solving it yourself first. Interviewers care more about how you explain the approach than about the finished code.
Watch the core idea of this problem step by step. Change the input and press Visualize.
Explained in the lesson Dynamic Programming (1-D).
Run your code to see results here.