Decode Ways II solution explained
Decode Ways II counts how many letter messages a string of digits could stand for, where 1 to 26 map to A to Z and a '*' can be any digit from 1 to 9, with the answer modulo 1,000,000,007. Use the same DP as the plain version, ways(i) = single(s[i]) × ways(i - 1) + pair(s[i - 1], s[i]) × ways(i - 2), where single and pair now return how many letters a character or a two-character chunk can be instead of 0 or 1. That is O(n) time and O(1) space.
By Evin JohnPublished 8 min read
The problem, in plain terms
Letters were turned into numbers, A as 1 up to Z as 26, and the numbers were written next to each other without separators. Some digits were then smudged and replaced with a star, which stands for any single digit from 1 to 9 (never 0). Given the resulting string of digits and stars, count how many different letter messages it could have come from. A chunk with a leading zero, like 05, is not a letter, and a lone 0 is not a letter either. Return the count modulo 1,000,000,007.
*0 -> 2 only 10 or 20; the 0 cannot stand alone
*7 -> 10 9 ways as two letters (* then G), plus 17 as one letter
1*2 -> 20
*1* -> 180Check *7 by hand to make sure the rules are clear: reading the star and the 7 separately gives 9 messages, one for each digit the star can be, and reading them together only works as 17, because 27 to 97 are too large. That gives 10.
Why it is asked
Most candidates have seen the plain decode problem. The wildcard version tests whether you understand that solution well enough to change it instead of starting over, and whether you can enumerate cases cleanly without a tangle of conditions. The counting rules for a star next to a 1, a 2 or another star are where people lose points, so a clear helper function is worth a lot.
Brute force
Replace every star with each digit from 1 to 9, decode every resulting plain string with the classic DP, and add the results. With k stars that is 9^k plain strings, so it explodes quickly, but it is a perfect reference for testing on short inputs, and that is exactly how the code below was checked.
The optimal approach: weighted decode DP
Pattern: linear dynamic programming with counted transitions. Let ways(i) be the number of readings of the first i characters. The last letter of a reading is either the last character alone or the last two characters together. In the plain version each option is allowed or not. Here each option comes with a number of letters it can be, so multiply: ways(i) = single(last char) × ways(i - 1) + pair(last two chars) × ways(i - 2). Everything hard lives in the two helper functions.
| First | Second | Count | Which numbers |
|---|---|---|---|
| * | * | 15 | 11 to 19 and 21 to 26 |
| * | 0 to 6 | 2 | 1x and 2x |
| * | 7 to 9 | 1 | only 1x |
| 1 | * | 9 | 11 to 19 |
| 2 | * | 6 | 21 to 26 |
| 1 | digit | 1 | 10 to 19 are all letters |
| 2 | digit | 1 if the digit is 0 to 6, else 0 | 20 to 26 |
| 0 or 3 to 9 | anything | 0 | no letter starts that way |
Two lines in that table are easy to get wrong. A star followed by a star is 15, not 17: the first star can only be 1 or 2 to make a two-digit letter, and the second star cannot be 0, which removes 10 and 20. And a star before 0 is 2, not 1, because both 10 and 20 work.
MOD = 10**9 + 7
def single(ch):
"""Ways this one character can be a letter on its own."""
if ch == "*":
return 9 # 1 to 9
return 0 if ch == "0" else 1
def pair(a, b):
"""Ways the two characters a, b can be one letter (10 to 26)."""
if a == "*" and b == "*":
return 15 # 11-19 and 21-26
if a == "*":
return 2 if b <= "6" else 1 # 1b and 2b, or only 1b
if b == "*":
if a == "1":
return 9 # 11-19
if a == "2":
return 6 # 21-26
return 0
return 1 if "10" <= a + b <= "26" else 0
def num_decodings(s):
before, last = 1, single(s[0]) # ways for prefixes of length i-1 and i
for i in range(1, len(s)):
now = (single(s[i]) * last + pair(s[i - 1], s[i]) * before) % MOD
before, last = last, now
return lastThe starting values matter. Before any character, there is one way to read nothing, which is why before starts at 1. After the first character, the count is single of that character, which is 0 if it is a 0. Every later step only needs the last two counts, so the whole table collapses into two numbers. The string comparison in the last line works because both sides are two-character digit strings, so they sort the same way as the numbers they spell.
JavaScript version
The JavaScript code folds the pair table into a few nested conditions organized by the first character. The counts are reduced every step, so each product stays below about 2.5 × 10^10, well inside the range where JavaScript numbers are exact. In C++ or Java you would use 64-bit integers for the same reason.
function numDecodings(s) {
const MOD = 1000000007;
const single = (c) => (c === "*" ? 9 : c === "0" ? 0 : 1);
const pair = (a, b) => {
if (a === "*") return b === "*" ? 15 : b <= "6" ? 2 : 1;
if (a === "1") return b === "*" ? 9 : 1;
if (a === "2") return b === "*" ? 6 : b <= "6" ? 1 : 0;
return 0;
};
let before = 1, last = single(s[0]);
for (let i = 1; i < s.length; i++) {
// both products stay below 2.5e10, far inside the safe integer range
const now = (single(s[i]) * last + pair(s[i - 1], s[i]) * before) % MOD;
before = last;
last = now;
}
return last;
}Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Fill every star, decode each result | O(9^k × n) | O(n) |
| Recursion with memo on position | O(n) | O(n) memo plus O(n) stack |
| Rolling two-counter DP | O(n) | O(1) |
Edge cases to test
- A string that starts with 0: no readings, and the DP should return 0 rather than crash.
- A 0 after 3 to 9, like 30, which also kills every reading.
- A star right before a 0, which is 2 ways, and a star right after a 1 or a 2.
- Long runs of stars, which make the count wrap around the modulus many times.
- An empty string: the code above reads the first character, so agree up front whether empty input is possible and what it should return.
Common mistakes
- Letting a star be 0, which inflates counts like ** from 15 to 17 pairs.
- Counting a star before 7, 8 or 9 as 2 pair readings instead of 1.
- Forgetting that a 0 can never stand alone, even after a star.
- Taking the modulo only at the end; the true count is enormous long before the string ends.
- Writing one long chain of if statements inside the loop, which hides the case that is missing. Separate helpers make each rule testable on its own.
How to explain it out loud
Fictional example
- Candidate
- Without stars, ways at i is ways at i minus 1 if the last digit is a letter, plus ways at i minus 2 if the last two digits are a letter. The star doesn't change that structure, it just means each choice can be several letters.
- Candidate
- So I'll write two helpers that return counts instead of booleans: one character is 0, 1 or 9 letters, and a pair is up to 15 letters for two stars. Then I multiply each count by the matching earlier total.
- Candidate
- I only keep the last two totals, so it's linear time and constant space, and I take the modulo every step. Let me check star seven by hand first: nine separate readings plus seventeen, so ten.
Related problems
Another count over strings with a fixed set of letters, where the state is a few counters rather than a position pair, is Student Attendance Record II. For a string DP that asks yes or no about two strings instead of counting, try Scramble String. A DP with many predecessors per step, on a grid, is Minimum Path Cost in a Grid.
Where Natively helps in practice
Case tables like the one above are what you forget under pressure, so drilling them pays off. In a practice session on Mac or Windows, Natively can read the problem from a screenshot and write an approach and code you can compare with your own helpers, case by case. The transcript it keeps lets you hear whether you checked a small input by hand before coding. Learn more about an AI assistant for coding interview practice.
Questions people ask
How do you solve Decode Ways II?
Use the plain decode DP but weight each step: ways(i) = single(last char) × ways(i - 1) + pair(last two chars) × ways(i - 2), where single and pair count how many letters a character or a two-character chunk can be. Reduce modulo 1e9+7 each step.
How many ways can ** be decoded as one letter?
15. The two-digit letters are 10 to 26, but a star is 1 to 9, so the first star must be 1 or 2 and the second cannot be 0. That leaves 11 to 19 and 21 to 26.
What is the time complexity of Decode Ways II?
O(n) time and O(1) extra space, because each position needs only the counts for the previous one and two positions.
Why does *0 have two decodings?
A 0 can never be a letter by itself, so the star and the 0 must form one letter. The star can be 1 or 2, giving 10 or 20, which is two readings.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
