15% off all plans & roadmaps Use code
See plansDecode Ways
- LeetCode 91
- Medium
- Dynamic Programming (DP) Patterns
- 1D Array (Fibonacci Style)
Updated
TL;DR: Count the ways to split a digit string into codes 1 to 26. Each prefix count is the sum of two earlier counts, so a Fibonacci-style DP with two variables solves it in O(n) time and O(1) space.
Problem
A message is encoded as a string of digits. Each letter maps to a number: "1" is 'A', "2" is 'B', and so on up to "26", which is 'Z'.
Because some codes contain other codes ("2" and "5" versus "25"), one string can decode in several ways. For example, "11106" can become:
"AAJF"with the grouping(1, 1, 10, 6)"KJF"with the grouping(11, 10, 6)- The grouping
(1, 11, 06)is invalid, because"06"is not a code. Only"6"is.
Some strings cannot be decoded at all.
Given a string s made only of digits, return the number of ways to decode it. If there is no valid way, return 0. The test cases are built so the answer fits in a 32-bit integer.
Example 1
Input: s = "12" Output: 2 Explanation: "12" decodes as "AB" (1 2) or "L" (12).
Example 2
Input: s = "226" Output: 3 Explanation: "226" decodes as "BZ" (2 26), "VF" (22 6) or "BBF" (2 2 6).
Example 3
Input: s = "06" Output: 0 Explanation: "06" cannot map to "F", because "06" is not the same code as "6". The string has no valid encoding, so the answer is 0.
Constraints
1 <= s.length <= 100scontains only digits and may contain leading zeros.
Constraints that matter
s.length <= 100means a recursion that branches twice per digit can reach billions of calls in the worst case, so you need to share work between branches.- The recursion depth is at most 100, so recursion is safe in every language, including Python's default limit.
- Digits may be zero, and
0has no code alone. A zero is only usable as the second digit of10or20, so every transition needs an explicit zero check. - The answer fits in 32 bits, but counts for long prefixes can be larger when a later zero kills the string. Intermediate sums can overflow
intin some languages, so know what your language does on overflow. - Only the last two prefix counts are ever read, which lets you drop the full table and use O(1) extra space.
Hints
Hint 1
This is a counting problem on a string where each decision looks only at the last one or two digits.
Hint 2
Walk the string from the left.
Solution
Intuition
This is a counting problem on a string where each decision looks only at the last one or two digits. That is the signal for dynamic programming on a 1D array, the same shape as Climbing Stairs. The last code in any valid decoding is either one digit or two digits, and those two cases never overlap.
It is like a ledger that keeps only the last two monthly totals. The variable prev2 is the older total, prev1 is the newer one, and each new total cur is built from both and replaces the oldest entry.
So let dp[i] be the number of ways to decode the first i characters. If the last code is the single digit s[i-1], it must be 1 to 9, and the rest of the work is dp[i-1]. If the last code is the pair s[i-2]s[i-1], it must be 10 to 26, and the rest is dp[i-2]. Add the two cases that are allowed.
The base case is dp[0] = 1. An empty prefix has exactly one decoding: the empty one. Without that value, the first pair such as 12 would not count its L decoding.
Zeros fall out of the rules for free. A 0 adds nothing as a single digit, and it adds dp[i-2] only when the digit before it makes 10 or 20.
The recurrence reads only dp[i-1] and dp[i-2]. You can keep two variables and roll them forward, exactly as in an iterative Fibonacci. The page builds up to that: plain recursion, then memoization to remove repeated work, then the rolling-variable version.
Worked example
Input: s = "11106" Output: 2 Explanation: The only valid groupings are (1, 1, 10, 6), which reads AAJF, and (11, 10, 6), which reads KJF. The zero must pair with the 1 before it as 10, and 06 is never a code. That leaves exactly two ways.
Approach 1: Brute force recursion
Walk the string from the left. At index i, try to take one digit, and try to take two digits. Count how many complete decodings each choice leads to, and add them.
A zero at the current index kills the branch, because no code starts with 0. Reaching the end of the string counts as one finished decoding. This is correct, and it is what you write first when you have not noticed the repeated work.
Steps
- Define
count(i)as the number of ways to decode the suffix starting at indexi. - If
i == n, return 1. The whole string has been consumed. - If
s[i] == '0', return 0. No code starts with zero. - Start
ways = count(i + 1)for taking one digit. - If a second digit exists and the pair is at most 26, add
count(i + 2). - Return
ways, and callcount(0)for the answer.
Dry run
Trace "11106" by suffix index.
count(5)returns 1 (end of string).count(4): digit6is fine, so it callscount(5)= 1. No second digit exists. Result 1.count(3):s[3]is0, so it returns 0.count(2): take1givescount(3)= 0. Pair10is valid, so addcount(4)= 1. Result 1.count(1): take1givescount(2)= 1. Pair11is valid, so addcount(3)= 0. Result 1.count(0): take1givescount(1)= 1. Pair11is valid, so addcount(2)= 1. Result 2.
Notice that count(2) and count(3) were each reached from two different parents. On longer strings that repeated work explodes.
Complexity
| Time | O(2^n) |
|---|---|
| Space | O(n) |
Here n is the length of s. Each call makes at most two recursive calls and the index grows by 1 or 2, so the call tree has at most 2^n nodes. The worst case, a string such as all ones, grows like the Fibonacci numbers, which is still exponential. The recursion depth is at most n, so the stack uses O(n) space.
PythonTested in our runner
class Solution:
def numDecodings(self, s: str) -> int:
n = len(s)
def count(i: int) -> int:
if i == n:
return 1
if s[i] == '0':
return 0
ways = count(i + 1)
if i + 1 < n and int(s[i:i + 2]) <= 26:
ways += count(i + 2)
return ways
return count(0)
JavaTested in our runner
class Solution {
public int numDecodings(String s) {
return count(s, 0);
}
private int count(String s, int i) {
int n = s.length();
if (i == n) {
return 1;
}
if (s.charAt(i) == '0') {
return 0;
}
int ways = count(s, i + 1);
if (i + 1 < n) {
int pair = (s.charAt(i) - '0') * 10 + (s.charAt(i + 1) - '0');
if (pair <= 26) {
ways += count(s, i + 2);
}
}
return ways;
}
}
C++Tested in our runner
class Solution {
public:
int numDecodings(string s) {
return count(s, 0);
}
private:
int count(const string& s, int i) {
int n = s.size();
if (i == n) {
return 1;
}
if (s[i] == '0') {
return 0;
}
int ways = count(s, i + 1);
if (i + 1 < n) {
int pair = (s[i] - '0') * 10 + (s[i + 1] - '0');
if (pair <= 26) {
ways += count(s, i + 2);
}
}
return ways;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {number}
*/
var numDecodings = function(s) {
const n = s.length;
const count = (i) => {
if (i === n) {
return 1;
}
if (s[i] === '0') {
return 0;
}
let ways = count(i + 1);
if (i + 1 < n && Number(s.substring(i, i + 2)) <= 26) {
ways += count(i + 2);
}
return ways;
};
return count(0);
};
GoTested in our runner
func numDecodings(s string) int {
n := len(s)
var count func(i int) int
count = func(i int) int {
if i == n {
return 1
}
if s[i] == '0' {
return 0
}
ways := count(i + 1)
if i+1 < n {
pair := int(s[i]-'0')*10 + int(s[i+1]-'0')
if pair <= 26 {
ways += count(i + 2)
}
}
return ways
}
return count(0)
}
C#Tested in our runner
public class Solution {
public int numDecodings(string s) {
return Count(s, 0);
}
private int Count(string s, int i) {
int n = s.Length;
if (i == n) {
return 1;
}
if (s[i] == '0') {
return 0;
}
int ways = Count(s, i + 1);
if (i + 1 < n) {
int pair = (s[i] - '0') * 10 + (s[i + 1] - '0');
if (pair <= 26) {
ways += Count(s, i + 2);
}
}
return ways;
}
}
Approach 2: Top-down memoization
What's slow: the recursion recomputes the same suffix many times. In the trace above, count(2) and count(3) each ran twice. The number of distinct suffixes is only n + 1, yet the call tree grows exponentially.
The insight that fixes it: count(i) depends only on i, never on the path taken to reach it. Store each result the first time you compute it and return the stored value afterward. Each index is then solved once.
Steps
- Create a
memoarray of sizen + 1, filled with -1 for not computed. - Write
count(i)as before: return 1 at the end, return 0 on a'0'. - At the top of
count(i), returnmemo[i]if it is not -1. - Compute
waysfromcount(i + 1)and, when the pair is 10 to 26,count(i + 2). - Store
waysinmemo[i]before returning it. - Return
count(0).
Dry run
Same string, "11106", with a cache. Calls in order of first computation:
count(0)callscount(1), which callscount(2), which callscount(3).count(3)sees0and storesmemo[3] = 0.count(2)then callscount(4), which callscount(5) = 1. It storesmemo[4] = 1, thenmemo[2] = 0 + 1 = 1.count(1)needscount(3)for the pair11. This is a cache hit, 0. It storesmemo[1] = 1 + 0 = 1.count(0)needscount(2)for the pair11. Another cache hit, 1. Result1 + 1 = 2.
Two recomputations became two lookups.
Complexity
| Time | O(n) |
|---|---|
| Space | O(n) |
Here n is the length of s. There are n + 1 distinct states, and each is computed once with a constant number of operations, so the time is O(n). The memo array holds n + 1 integers and the recursion depth is at most n, so the space is O(n).
PythonTested in our runner
class Solution:
def numDecodings(self, s: str) -> int:
n = len(s)
memo = [-1] * (n + 1)
def count(i: int) -> int:
if i == n:
return 1
if s[i] == '0':
return 0
if memo[i] != -1:
return memo[i]
ways = count(i + 1)
if i + 1 < n and int(s[i:i + 2]) <= 26:
ways += count(i + 2)
memo[i] = ways
return ways
return count(0)
JavaTested in our runner
class Solution {
public int numDecodings(String s) {
int[] memo = new int[s.length() + 1];
java.util.Arrays.fill(memo, -1);
return count(s, 0, memo);
}
private int count(String s, int i, int[] memo) {
int n = s.length();
if (i == n) {
return 1;
}
if (s.charAt(i) == '0') {
return 0;
}
if (memo[i] != -1) {
return memo[i];
}
int ways = count(s, i + 1, memo);
if (i + 1 < n) {
int pair = (s.charAt(i) - '0') * 10 + (s.charAt(i + 1) - '0');
if (pair <= 26) {
ways += count(s, i + 2, memo);
}
}
memo[i] = ways;
return ways;
}
}
C++Tested in our runner
class Solution {
public:
int numDecodings(string s) {
vector<int> memo(s.size() + 1, -1);
return count(s, 0, memo);
}
private:
int count(const string& s, int i, vector<int>& memo) {
int n = s.size();
if (i == n) {
return 1;
}
if (s[i] == '0') {
return 0;
}
if (memo[i] != -1) {
return memo[i];
}
int ways = count(s, i + 1, memo);
if (i + 1 < n) {
int pair = (s[i] - '0') * 10 + (s[i + 1] - '0');
if (pair <= 26) {
ways += count(s, i + 2, memo);
}
}
memo[i] = ways;
return ways;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {number}
*/
var numDecodings = function(s) {
const n = s.length;
const memo = new Array(n + 1).fill(-1);
const count = (i) => {
if (i === n) {
return 1;
}
if (s[i] === '0') {
return 0;
}
if (memo[i] !== -1) {
return memo[i];
}
let ways = count(i + 1);
if (i + 1 < n && Number(s.substring(i, i + 2)) <= 26) {
ways += count(i + 2);
}
memo[i] = ways;
return ways;
};
return count(0);
};
GoTested in our runner
func numDecodings(s string) int {
n := len(s)
memo := make([]int, n+1)
for i := range memo {
memo[i] = -1
}
var count func(i int) int
count = func(i int) int {
if i == n {
return 1
}
if s[i] == '0' {
return 0
}
if memo[i] != -1 {
return memo[i]
}
ways := count(i + 1)
if i+1 < n {
pair := int(s[i]-'0')*10 + int(s[i+1]-'0')
if pair <= 26 {
ways += count(i + 2)
}
}
memo[i] = ways
return ways
}
return count(0)
}
C#Tested in our runner
public class Solution {
public int numDecodings(string s) {
int[] memo = new int[s.Length + 1];
Array.Fill(memo, -1);
return Count(s, 0, memo);
}
private int Count(string s, int i, int[] memo) {
int n = s.Length;
if (i == n) {
return 1;
}
if (s[i] == '0') {
return 0;
}
if (memo[i] != -1) {
return memo[i];
}
int ways = Count(s, i + 1, memo);
if (i + 1 < n) {
int pair = (s[i] - '0') * 10 + (s[i + 1] - '0');
if (pair <= 26) {
ways += Count(s, i + 2, memo);
}
}
memo[i] = ways;
return ways;
}
}

Solution pattern
1D Array (Fibonacci Style)
Approach 3: Bottom-up DP with two variablesOptimal1D Array (Fibonacci Style)
What's slow: memoization is linear in time, but it still keeps an O(n) table and an O(n) call stack. Each state reads only the two states immediately before it, so older entries are dead weight.
The insight that fixes it: fill the prefix counts from left to right and keep only the last two. Let prev2 be dp[i-2] and prev1 be dp[i-1]. Each step computes cur from them, then slides the window forward by one. There is no recursion and no array.
Steps
- Set
prev2 = 1fordp[0], the empty prefix. - Set
prev1 = 1ifs[0]is not'0', else 0. This isdp[1]. - For each
ifrom 2 ton, setcur = 0. - If
s[i-1]is not'0', addprev1tocur. - Compute the pair
s[i-2]s[i-1]as a number. If it is 10 to 26, addprev2tocur. - Slide the window:
prev2 = prev1, thenprev1 = cur. - After the loop, return
prev1, which isdp[n].
Dry run
Trace "11106". Start with prev2 = dp[0] = 1 and prev1 = dp[1] = 1, since s[0] is 1.
| i | single digit s[i-1] | pair | single adds | pair adds | cur (dp[i]) | prev2, prev1 after |
|---|---|---|---|---|---|---|
| 2 | 1 | 11 | prev1 = 1 | prev2 = 1 | 2 | 1, 2 |
| 3 | 1 | 11 | prev1 = 2 | prev2 = 1 | 3 | 2, 3 |
| 4 | 0 | 10 | none (zero) | prev2 = 2 | 2 | 3, 2 |
| 5 | 6 | 06 = 6, invalid | prev1 = 2 | none | 2 | 2, 2 |
The loop ends with prev1 = 2, which matches the expected output. Row 4 shows the zero rule at work: dp[4] drops from 3 to 2, because the 0 can only join the 1 before it. Row 5 shows that 06 contributes nothing, so dp[5] inherits dp[4] unchanged.
Complexity
| Time | O(n) |
|---|---|
| Space | O(1) |
Here n is the length of s. The loop runs n - 1 times, and each iteration does a constant number of digit comparisons and additions, so the time is O(n). Only the variables prev1, prev2 and cur are stored, regardless of n, so the extra space is O(1).
PythonTested in our runner
class Solution:
def numDecodings(self, s: str) -> int:
n = len(s)
prev2 = 1 # dp[0]: empty prefix
prev1 = 0 if s[0] == '0' else 1 # dp[1]
for i in range(2, n + 1):
cur = 0
if s[i - 1] != '0':
cur += prev1
pair = int(s[i - 2:i])
if 10 <= pair <= 26:
cur += prev2
prev2 = prev1
prev1 = cur
return prev1
JavaTested in our runner
class Solution {
public int numDecodings(String s) {
int n = s.length();
int prev2 = 1; // dp[0]
int prev1 = s.charAt(0) == '0' ? 0 : 1; // dp[1]
for (int i = 2; i <= n; i++) {
int cur = 0;
if (s.charAt(i - 1) != '0') {
cur += prev1;
}
int pair = (s.charAt(i - 2) - '0') * 10 + (s.charAt(i - 1) - '0');
if (pair >= 10 && pair <= 26) {
cur += prev2;
}
prev2 = prev1;
prev1 = cur;
}
return prev1;
}
}
C++Tested in our runner
class Solution {
public:
int numDecodings(string s) {
int n = s.size();
// unsigned wraps safely if a prefix count is huge but the answer is 0
unsigned int prev2 = 1; // dp[0]
unsigned int prev1 = s[0] == '0' ? 0 : 1; // dp[1]
for (int i = 2; i <= n; i++) {
unsigned int cur = 0;
if (s[i - 1] != '0') {
cur += prev1;
}
int pair = (s[i - 2] - '0') * 10 + (s[i - 1] - '0');
if (pair >= 10 && pair <= 26) {
cur += prev2;
}
prev2 = prev1;
prev1 = cur;
}
return (int)prev1;
}
};
JavaScriptTested in our runner
/**
* @param {string} s
* @return {number}
*/
var numDecodings = function(s) {
const n = s.length;
let prev2 = 1; // dp[0]
let prev1 = s[0] === '0' ? 0 : 1; // dp[1]
for (let i = 2; i <= n; i++) {
let cur = 0;
if (s[i - 1] !== '0') {
cur += prev1;
}
const pair = (s.charCodeAt(i - 2) - 48) * 10 + (s.charCodeAt(i - 1) - 48);
if (pair >= 10 && pair <= 26) {
cur += prev2;
}
prev2 = prev1;
prev1 = cur;
}
return prev1;
};
GoTested in our runner
func numDecodings(s string) int {
n := len(s)
prev2 := 1 // dp[0]
prev1 := 1 // dp[1]
if s[0] == '0' {
prev1 = 0
}
for i := 2; i <= n; i++ {
cur := 0
if s[i-1] != '0' {
cur += prev1
}
pair := int(s[i-2]-'0')*10 + int(s[i-1]-'0')
if pair >= 10 && pair <= 26 {
cur += prev2
}
prev2 = prev1
prev1 = cur
}
return prev1
}
C#Tested in our runner
public class Solution {
public int numDecodings(string s) {
int n = s.Length;
int prev2 = 1; // dp[0]
int prev1 = s[0] == '0' ? 0 : 1; // dp[1]
for (int i = 2; i <= n; i++) {
int cur = 0;
if (s[i - 1] != '0') {
cur += prev1;
}
int pair = (s[i - 2] - '0') * 10 + (s[i - 1] - '0');
if (pair >= 10 && pair <= 26) {
cur += prev2;
}
prev2 = prev1;
prev1 = cur;
}
return prev1;
}
}
Common mistakes
- Adding
dp[i-1]without checkings[i-1] != '0'. A lone zero has no code, so the single-digit branch must add nothing. The fix is the explicit zero test before that addition. - Testing the pair with
int(s[i-2:i]) <= 26alone."06"is 6, which passes, but06is not a code. Require10 <= pair <= 26, or check that the first digit is not zero. - Starting with
dp[0] = 0. The empty prefix must count as 1 way, or every pair such as12loses its two-digit decoding. Setdp[0] = 1. - Reading
s[i-2]wheni = 1. Start the loop ati = 2and setdp[1]before it, or guard the pair check withi >= 2. - Returning early with 0 only when the first character is zero. Zeros later in the string, as in
"100"or"30", also give 0, and the recurrence handles them only if both branches reject them. Do not special-case them away. - Using a greedy rule such as always taking two digits when possible. For
"226"that gives22 6and misses the other two decodings. You must count both branches at every step. - Updating the window in the wrong order, such as
prev1 = curbeforeprev2 = prev1. That destroys the oldprev1. Moveprev2first, thenprev1.
Edge cases
"0": no code starts with zero, so the answer is 0."06": a leading zero makes the whole string undecodable, so the answer is 0."10": the zero is used by the pair10, so the answer is 1, not 2."100": the final0has no valid partner, since00is not a code. The answer is 0."27": 27 is above 26, so only2 7works. The answer is 1."1": a single non-zero digit gives 1 and the loop never runs.- A hundred ones: the count is large, and tests keep the answer within 32 bits. Pay attention to overflow only if you add a custom large test.
Follow-ups interviewers ask
- Can you do it in O(1) extra space?
- Yes. Each
dp[i]reads onlydp[i-1]anddp[i-2], so keep two variables and slide them forward. That is the third approach on this page. Time stays O(n) and the table disappears. - What if the answer can be huge and you must return it modulo 10^9 + 7?
- Apply the modulo after every addition,
cur = (cur + prev1) % MOD. Use a 64-bit type in Java, C++ and C# so the sum of two values below MOD cannot overflow. The recurrence does not change. - What if the string can contain
*as a wildcard for any digit 1 to 9? - That is Decode Ways II. Keep the same recurrence, but each transition multiplies by the number of digits the wildcard can stand for. For example
*alone gives 9 single choices, and1*gives 9 pairs. Work mod 10^9 + 7 because the counts grow quickly.
Decode Ways FAQ
What is the time complexity of Decode Ways?
The optimal DP runs in O(n) time, where n is the length of the string. It visits each position once and does constant work per position. Plain recursion without memoization is exponential, up to O(2^n).
Why use dynamic programming for Decode Ways?
The count for a prefix depends only on the counts for the prefixes one and two characters shorter. Those subproblems repeat across many branches in plain recursion. DP computes each one once, which turns an exponential search into a linear scan.
Can Decode Ways be solved in O(1) extra space?
Yes. The recurrence uses only dp[i-1] and dp[i-2], so two integer variables replace the array. The input string is read-only and is not counted as extra space.
Why does the empty prefix count as 1 way?
It acts as the identity for the sum. When the first two digits form a valid code such as 12, that code leaves an empty prefix behind, and it must contribute one decoding. Setting dp[0] = 0 would drop those counts.
How does Decode Ways handle zeros?
A zero never counts as a single digit. It only works as the second digit of 10 or 20, which the pair check allows through dp[i-2]. If the zero is preceded by anything else, both branches add nothing and the count for that prefix becomes 0.
How is Decode Ways related to Climbing Stairs?
Both use the recurrence f(i) = f(i-1) + f(i-2). In Climbing Stairs both steps are always allowed. In Decode Ways each step is allowed only when the one-digit or two-digit code is valid.
Asked at
See which companies ask this — Pro
Related problems
- House Robber · same technique: 1D Array (Fibonacci Style)
- House Robber II · same technique: 1D Array (Fibonacci Style)
- Integer Break · same technique: 1D Array (Fibonacci Style)
- House Robber III · same technique: 1D Array (Fibonacci Style)
- Delete and Earn · same technique: 1D Array (Fibonacci Style)
- Distinct Subsequences · next harder, same pattern
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns