A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
"AAJF" with the grouping (1 1 10 6)
"KJF" with the grouping (11 10 6)
Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
Since the answer may be very large, return it modulo109 + 7.
Example 1:
Input: s = "*"
Output: 9
Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
Hence, there are a total of 9 ways to decode "*".
Example 2:
Input: s = "1*"
Output: 18
Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
Example 3:
Input: s = "2*"
Output: 15
Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
"21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
Problem summary: A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> "1" 'B' -> "2" ... 'Z' -> "26" To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into: "AAJF" with the grouping (1 1 10 6) "KJF" with the grouping (11 10 6) Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06". In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent. Given
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
"*"
Example 2
"1*"
Example 3
"2*"
Related Problems
Decode Ways (decode-ways)
Number of Ways to Separate Numbers (number-of-ways-to-separate-numbers)
Number of Ways to Divide a Long Corridor (number-of-ways-to-divide-a-long-corridor)
Step 02
Core Insight
What unlocks the optimal approach
No official hints in dataset. Start from constraints and look for a monotonic or reusable state.
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #639: Decode Ways II
class Solution {
private static final int MOD = 1000000007;
public int numDecodings(String s) {
int n = s.length();
char[] cs = s.toCharArray();
// dp[i - 2], dp[i - 1], dp[i]
long a = 0, b = 1, c = 0;
for (int i = 1; i <= n; i++) {
// 1 digit
if (cs[i - 1] == '*') {
c = 9 * b % MOD;
} else if (cs[i - 1] != '0') {
c = b;
} else {
c = 0;
}
// 2 digits
if (i > 1) {
if (cs[i - 2] == '*' && cs[i - 1] == '*') {
c = (c + 15 * a) % MOD;
} else if (cs[i - 2] == '*') {
if (cs[i - 1] > '6') {
c = (c + a) % MOD;
} else {
c = (c + 2 * a) % MOD;
}
} else if (cs[i - 1] == '*') {
if (cs[i - 2] == '1') {
c = (c + 9 * a) % MOD;
} else if (cs[i - 2] == '2') {
c = (c + 6 * a) % MOD;
}
} else if (cs[i - 2] != '0' && (cs[i - 2] - '0') * 10 + cs[i - 1] - '0' <= 26) {
c = (c + a) % MOD;
}
}
a = b;
b = c;
}
return (int) c;
}
}
// Accepted solution for LeetCode #639: Decode Ways II
const mod int = 1e9 + 7
func numDecodings(s string) int {
n := len(s)
// dp[i - 2], dp[i - 1], dp[i]
a, b, c := 0, 1, 0
for i := 1; i <= n; i++ {
// 1 digit
if s[i-1] == '*' {
c = 9 * b % mod
} else if s[i-1] != '0' {
c = b
} else {
c = 0
}
// 2 digits
if i > 1 {
if s[i-2] == '*' && s[i-1] == '*' {
c = (c + 15*a) % mod
} else if s[i-2] == '*' {
if s[i-1] > '6' {
c = (c + a) % mod
} else {
c = (c + 2*a) % mod
}
} else if s[i-1] == '*' {
if s[i-2] == '1' {
c = (c + 9*a) % mod
} else if s[i-2] == '2' {
c = (c + 6*a) % mod
}
} else if s[i-2] != '0' && (s[i-2]-'0')*10+s[i-1]-'0' <= 26 {
c = (c + a) % mod
}
}
a, b = b, c
}
return c
}
# Accepted solution for LeetCode #639: Decode Ways II
class Solution:
def numDecodings(self, s: str) -> int:
mod = int(1e9 + 7)
n = len(s)
# dp[i - 2], dp[i - 1], dp[i]
a, b, c = 0, 1, 0
for i in range(1, n + 1):
# 1 digit
if s[i - 1] == "*":
c = 9 * b % mod
elif s[i - 1] != "0":
c = b
else:
c = 0
# 2 digits
if i > 1:
if s[i - 2] == "*" and s[i - 1] == "*":
c = (c + 15 * a) % mod
elif s[i - 2] == "*":
if s[i - 1] > "6":
c = (c + a) % mod
else:
c = (c + 2 * a) % mod
elif s[i - 1] == "*":
if s[i - 2] == "1":
c = (c + 9 * a) % mod
elif s[i - 2] == "2":
c = (c + 6 * a) % mod
elif (
s[i - 2] != "0"
and (ord(s[i - 2]) - ord("0")) * 10 + ord(s[i - 1]) - ord("0") <= 26
):
c = (c + a) % mod
a, b = b, c
return c
// Accepted solution for LeetCode #639: Decode Ways II
/**
* [0639] Decode Ways II
*
* A message containing letters from A-Z can be encoded into numbers using the following mapping:
*
* 'A' -> "1"
* 'B' -> "2"
* ...
* 'Z' -> "26"
*
* To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" can be mapped into:
*
* "AAJF" with the grouping (1 1 10 6)
* "KJF" with the grouping (11 10 6)
*
* Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".
* In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.
* Given a string s consisting of digits and '*' characters, return the number of ways to decode it.
* Since the answer may be very large, return it modulo 10^9 + 7.
*
* Example 1:
*
* Input: s = "*"
* Output: 9
* Explanation: The encoded message can represent any of the encoded messages "1", "2", "3", "4", "5", "6", "7", "8", or "9".
* Each of these can be decoded to the strings "A", "B", "C", "D", "E", "F", "G", "H", and "I" respectively.
* Hence, there are a total of 9 ways to decode "*".
*
* Example 2:
*
* Input: s = "1*"
* Output: 18
* Explanation: The encoded message can represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19".
* Each of these encoded messages have 2 ways to be decoded (e.g. "11" can be decoded to "AA" or "K").
* Hence, there are a total of 9 * 2 = 18 ways to decode "1*".
*
* Example 3:
*
* Input: s = "2*"
* Output: 15
* Explanation: The encoded message can represent any of the encoded messages "21", "22", "23", "24", "25", "26", "27", "28", or "29".
* "21", "22", "23", "24", "25", and "26" have 2 ways of being decoded, but "27", "28", and "29" only have 1 way.
* Hence, there are a total of (6 * 2) + (3 * 1) = 12 + 3 = 15 ways to decode "2*".
*
*
* Constraints:
*
* 1 <= s.length <= 10^5
* s[i] is a digit or '*'.
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/decode-ways-ii/
// discuss: https://leetcode.com/problems/decode-ways-ii/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
const MOD: i64 = 1_000_000_007;
impl Solution {
// Credit: https://leetcode.com/problems/decode-ways-ii/discuss/1328922/Rust-DP-solution
pub fn num_decodings(s: String) -> i32 {
let s = s.chars().collect::<Vec<_>>();
let mut dp = (
1,
match s[0] {
'*' => 9,
'0' => 0,
_ => 1,
},
);
for i in 1..s.len() {
let n = if s[i] == '*' {
dp.0 * match s[i - 1] {
'*' => 15,
'1' => 9,
'2' => 6,
_ => 0,
} + dp.1 * 9
} else {
dp.0 * match s[i - 1] {
'*' if s[i] <= '6' => 2,
'2' if s[i] <= '6' => 1,
'*' | '1' => 1,
_ => 0,
} + if s[i] == '0' { 0 } else { dp.1 }
};
dp = (dp.1, n % MOD);
}
dp.1 as i32
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_0639_example_1() {
let s = "*".to_string();
let result = 9;
assert_eq!(Solution::num_decodings(s), result);
}
#[test]
fn test_0639_example_2() {
let s = "1*".to_string();
let result = 18;
assert_eq!(Solution::num_decodings(s), result);
}
#[test]
fn test_0639_example_3() {
let s = "2*".to_string();
let result = 15;
assert_eq!(Solution::num_decodings(s), result);
}
}
// Accepted solution for LeetCode #639: Decode Ways II
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #639: Decode Ways II
// class Solution {
//
// private static final int MOD = 1000000007;
//
// public int numDecodings(String s) {
// int n = s.length();
// char[] cs = s.toCharArray();
//
// // dp[i - 2], dp[i - 1], dp[i]
// long a = 0, b = 1, c = 0;
// for (int i = 1; i <= n; i++) {
// // 1 digit
// if (cs[i - 1] == '*') {
// c = 9 * b % MOD;
// } else if (cs[i - 1] != '0') {
// c = b;
// } else {
// c = 0;
// }
//
// // 2 digits
// if (i > 1) {
// if (cs[i - 2] == '*' && cs[i - 1] == '*') {
// c = (c + 15 * a) % MOD;
// } else if (cs[i - 2] == '*') {
// if (cs[i - 1] > '6') {
// c = (c + a) % MOD;
// } else {
// c = (c + 2 * a) % MOD;
// }
// } else if (cs[i - 1] == '*') {
// if (cs[i - 2] == '1') {
// c = (c + 9 * a) % MOD;
// } else if (cs[i - 2] == '2') {
// c = (c + 6 * a) % MOD;
// }
// } else if (cs[i - 2] != '0' && (cs[i - 2] - '0') * 10 + cs[i - 1] - '0' <= 26) {
// c = (c + a) % MOD;
// }
// }
//
// a = b;
// b = c;
// }
//
// return (int) c;
// }
// }
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O(n × m)
Space
O(n × m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.