Skip to content
Problem 639 · LeetCode 639(opens in a new tab)

Decode Ways II

HardDynamic programming

Letters are encoded as numbers: A is 1, B is 2, and so on up to Z, which is 26. A message of letters becomes a string of digits, and decoding means cutting the digits back into pieces of one or two digits that each name a letter. A piece may not start with 0, so 06 is not a letter.

This message may also contain *, a smudged digit that could have been any of 1 to 9 (never 0). Count how many letter strings the message s could decode to, over every choice of digit for every *. The count can be huge, so return it modulo 1,000,000,007.

Example 1

Input:  s = "*1*"
Output: 180
Why:    99 decodings end with a lone *, 81 end with the pair 1*
2 more examples and the constraints

Example 2

Input:  s = "3*"
Output: 9
Why:    31 to 39 are not letters, so only 3 then one more letter

Example 3

Input:  s = "*0"
Output: 2
Why:    the 0 must pair up, and only 10 and 20 work

Constraints

  • 1 ≤ s.length ≤ 100,000
  • Each character of s is a digit 0–9 or *

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. DP table over prefixesO(n)
  2. Two rolling countsO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 charactersVerdict
DP table over prefixesO(n)
Clear; stores every prefix
Two rolling countsO(n)
Best; constant memory

n = length of s.

Edge cases to test

  • A zero alone. "0" has no decoding: the answer is 0.
  • Star before a zero. "*0" can only be 10 or 20, so 2.
  • Two stars. A message of two stars has 81 readings as two single letters plus 15 as one pair: 96.
  • Zero after a big digit. "30" is 0: 30 is not a letter and 0 cannot stand alone.
  • Long input. Up to 100,000 characters: take the modulus at every step and avoid recursion.

Common mistakes

  • Letting * stand for 0, which gives 10 single-character options instead of 9.
  • Counting a pair of stars as 81 two-digit codes; only 11–19 and 21–26 are letters, so it is 15.
  • Multiplying in 32-bit integers, which overflows before the modulus is applied.

How to talk through it

  1. 1Clarify. Can a star be 0? Is a leading zero in a pair allowed? Return modulo 10^9 + 7?
  2. 2Start from the classic. Without stars this is Decode Ways: dp[i] adds dp[i−1] and dp[i−2] when the last pieces are valid.
  3. 3Generalise the weights. Replace valid or invalid with a count of letters for one character and for a pair.
  4. 4Save memory. Only the last two counts are needed, so roll them.
  5. 5Test out loud. Run "*0", "30" and a message of two stars by hand.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?