A message was turned into digits by replacing each letter with its place in the alphabet: A is 1, B is 2, and so on up to Z, which is 26. The separators were lost, so a string of digits can often be read back in more than one way. For example, 12 could be AB or L.
Given the digit string s, return how many different letter strings it could have come from. A code never starts with 0, so 06 is not F. If s cannot be read at all, return 0. The answer always fits in a 32-bit integer.
Example 1
Input: s = "2611" Output: 4 Why: 2 6 1 1, 26 1 1, 2 6 11 and 26 11
2 more examples and the constraints
Example 2
Input: s = "105" Output: 1 Why: the 0 must pair with the 1 before it: 10 5
Example 3
Input: s = "30" Output: 0 Why: 30 is above 26, and 0 alone is not a letter
Constraints
- 1 ≤ length of s ≤ 100
- s holds only the digits 0 to 9, and may start with 0
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain recursionO(2ⁿ)
- DP table over prefixesO(n)
- Two rolling countsO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 digits | Verdict |
|---|---|---|---|
| Plain recursion | O(2ⁿ) | Shows the recurrence; too slow | |
| DP table over prefixes | O(n) | Passes; O(n) memory | |
| Two rolling counts | O(n) | Best; constant memory |
n = number of digits in s.
Edge cases to test
- Starts with 0. "06" or "0" gives 0: no letter has a code that begins with 0.
- Zero after a digit above 2. "30" gives 0 because 30 is not a letter and 0 cannot stand alone.
- Two zeros in a row. "1001" gives 0: the second 0 has nothing to pair with.
- Pairs at the boundary. "26" gives 2, but "27" gives 1, since 27 is past Z.
- Long runs of 1s. Every pair is valid, so the counts follow the Fibonacci numbers; 25 ones give 121,393.
Common mistakes
- Counting
0as a letter on its own, or treating "05" as a valid two-digit code. - Accepting any two digits up to 26 without checking the first is not 0, so "06" counts as F.
- Starting dp[0] at 0 instead of 1, which makes every count 0.
How to talk through it
- 1Clarify. Can the string start with 0? What should an impossible string return? Does the answer fit in an int?
- 2Find the recurrence. The last letter used one digit or two. Each choice is allowed only when it is a real code.
- 3Say why recursion is slow. The same suffix is decoded from many split points, so the work grows exponentially.
- 4Fill it left to right. dp over prefixes, then notice only the last two values matter and keep two counters.
- 5Test out loud. Run "105", "30" and "2611" by hand: 1, 0 and 4.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?