Decode Ways
Medium · Dynamic programming
Jump to codeA digit string encodes letters with 1 → A through 26 → Z. Count valid decodings. A zero cannot stand alone, and codes cannot begin with zero. The input is nonempty.
Examples
Example 1
s = "12"
Output: 2
Example 2
s = "226"
Output: 3
Constraints
- 1 <= s.length <= 100
- s consists of digits
- The result fits a signed 32-bit integer.
Need a hint?
The final letter uses either one valid digit or two valid digits.
Asked in real interviews
Candidates reported versions of Decode Ways from these company interviews. Some company questions are locked and open with Premium or XP.
Browse all real coding interview questionsSolution approach
Set the empty-prefix count to one. For each prefix, add the previous count when its last digit is not zero. Also add the count two positions back when the last two digits form 10 through 26. Keep two previous counts; invalid zeros naturally give zero ways.
Complexity
O(n) time and O(1) auxiliary space.
Python reference solution
def numDecodings(s):
before, current = 1, 1
for i, char in enumerate(s):
following = current if char != '0' else 0
if i > 0 and '10' <= s[i - 1:i + 1] <= '26':
following += before
before, current = current, following
return current
JavaScript solution
function numDecodings(s) {
let before = 1, current = 1;
for (let i = 0; i < s.length; i++) {
let next = s[i] !== '0' ? current : 0;
if (i > 0 && (s[i - 1] === '1' || (s[i - 1] === '2' && s[i] <= '6'))) next += before;
before = current; current = next;
}
return current;
}
Java solution
import java.util.*;
class Solution {
public int numDecodings(String s) {
int before = 1, current = 1;
for (int i = 0; i < s.length(); i++) {
int next = s.charAt(i) != '0' ? current : 0;
if (i > 0 && (s.charAt(i - 1) == '1' || (s.charAt(i - 1) == '2' && s.charAt(i) <= '6'))) next += before;
before = current; current = next;
}
return current;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numDecodings(string s) {
int before = 1, current = 1;
for (int i = 0; i < (int)s.size(); i++) {
int next = s[i] != '0' ? current : 0;
if (i > 0 && (s[i - 1] == '1' || (s[i - 1] == '2' && s[i] <= '6'))) next += before;
before = current; current = next;
}
return current;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ "12" ]
2
[ "226" ]
3
[ "06" ]
0
[ "10" ]
1
[ "27" ]
1
Drafts are saved per language in this browser when storage is available.