Decode Ways (LeetCode 91): Solution and Explanation
Letters A through Z are encoded as the numbers 1 through 26, and a message has been turned into a string of digits with no separators. Count how many different letter sequences could have produced that digit string.
Watch it run step by step
Try your own input and write the code →Intuition
At any position you have at most two choices: read one digit as a letter, or read two digits as a letter. The brute force explores both choices recursively, which branches like Fibonacci and takes exponential time on long strings of 1s and 2s.
What makes it fast is that the number of ways to decode the rest of the string depends only on where you are, not on the choices that led there. If dp[i] is the number of ways to decode s[i:], then reading one digit contributes dp[i + 1] and reading two digits contributes dp[i + 2]. This is the same recurrence as climbing stairs, with validity checks added.
The checks are where the problem bites. A single digit is valid unless it is 0, because no letter maps to 0. A two-digit chunk is valid only when it is between 10 and 26, which means the first digit is 1, or the first digit is 2 and the second is 0 through 6. A zero can therefore only appear as the second half of 10 or 20. Building the answers from the end of the string backward, with dp[len(s)] = 1 for the empty suffix, handles every case cleanly.
Approach: Bottom-up DP from the right
- Start a map
dpwithdp[len(s)] = 1, meaning there is one way to decode an empty suffix. - Walk
ifromlen(s) - 1down to 0. - If
s[i]is '0', setdp[i] = 0because no decoding can start with a zero. - Otherwise set
dp[i] = dp[i + 1]for readings[i]as a single letter. - If a next digit exists and the pair is 10 to 19, or 20 to 26, add
dp[i + 2]for reading two digits. - Return
dp[0].
Step-by-step example
s = "226"
- Start with
dp[3] = 1. - i = 2, digit '6':
dp[2] = dp[3] = 1. There is no next digit, so nothing is added. - i = 1, digit '2':
dp[1] = dp[2] = 1. The pair "26" is valid, so adddp[3], givingdp[1] = 2. - i = 0, digit '2':
dp[0] = dp[1] = 2. The pair "22" is valid, so adddp[2] = 1, givingdp[0] = 3. - Return 3: the decodings are BBF (2,2,6), BZ (2,26) and VF (22,6).
Code: Python, Java, C++
1class Solution:
2 def numDecodings(self, s: str) -> int:
3 dp = { len(s): 1 }
4
5 for i in range(len(s) - 1, -1, -1):
6 if s[i] == "0":
7 dp[i] = 0
8 else:
9 dp[i] = dp[i + 1]
10
11 if (i + 1 < len(s) and (s[i] == "1" or
12 s[i] == "2" and s[i + 1] in "0123456")):
13 dp[i] += dp[i + 2]
14 return dp[0]1class Solution {
2 public int numDecodings(String s) {
3 int[] dp = new int[s.length() + 1];
4 dp[s.length()] = 1;
5
6 for (int i = s.length() - 1; i >= 0; i--) {
7 if (s.charAt(i) == '0') {
8 dp[i] = 0;
9 } else {
10 dp[i] = dp[i + 1];
11 }
12
13 if (i + 1 < s.length() && (s.charAt(i) == '1' || (s.charAt(i) == '2' && s.charAt(i + 1) >= '0' && s.charAt(i + 1) <= '6'))) {
14 dp[i] += dp[i + 2];
15 }
16 }
17 return dp[0];
18 }
19}1class Solution {
2public:
3 int numDecodings(string s) {
4 vector<int> dp(s.size() + 1, 0);
5 dp[s.size()] = 1;
6
7 for (int i = s.size() - 1; i >= 0; i--) {
8 if (s[i] == '0') {
9 dp[i] = 0;
10 } else {
11 dp[i] = dp[i + 1];
12 }
13
14 if (i + 1 < s.size() && (s[i] == '1' || (s[i] == '2' && s[i + 1] >= '0' && s[i + 1] <= '6'))) {
15 dp[i] += dp[i + 2];
16 }
17 }
18 return dp[0];
19 }
20};Time and space complexity
O(n)
Each index is processed once with constant work for the one-digit and two-digit checks.
O(n)
The dp map stores one count per index. Since each entry only depends on the next two, it can be cut to O(1) with two variables.
Other approaches
Constant-space rolling variables (time O(n), space O(1))
Keep only dp[i + 1] and dp[i + 2] in two variables and shift them as i moves left. Same logic, same time, without the map.
Top-down recursion with memoization (time O(n), space O(n))
Recurse from index 0, trying one and two digit reads and caching by index. It is a direct translation of the choice tree but uses recursion depth up to n.
Common mistakes
- Treating '0' as a valid single digit, which overcounts strings like "10" and "06".
- Accepting pairs like "27" or "30". The two-digit chunk must be 10 to 26, so check the first digit and, when it is 2, that the second is at most 6.
- Forgetting that a leading zero makes the whole answer 0, which the bottom-up loop handles automatically since
dp[0]becomes 0. - Getting the base case wrong.
dp[len(s)]must be 1 so that a valid final chunk contributes exactly one way.
Frequently asked questions
How does decode ways handle zeros?
A zero can never be decoded on its own, so any position holding '0' gets dp[i] = 0. A zero only survives as the second digit of 10 or 20, which the two-digit check allows. A string like "30" or "100" therefore returns 0.
Why is decode ways similar to climbing stairs?
Both count paths where each step moves forward one or two positions, so both follow a Fibonacci-like recurrence. Decode ways adds rules that disable a one-step or two-step move when the digits do not form a valid letter.
Can decode ways be solved in O(1) space?
Yes. Each entry needs only the next two entries, so two rolling variables are enough. The time stays O(n).
What is the time complexity of decode ways?
It is O(n) time, since each character is visited once and the checks are constant work. Space is O(n) with the map shown here, or O(1) with two rolling variables.