Digit Message Decodings

Medium · 1-D Dynamic Programming · about 25 min

A friend sends a secret note where each letter was replaced by its number: A = 1, B = 2, ..., Z = 26. The numbers were written next to each other with no spaces, so "12" could be "AB" (1, 2) or "L" (12).

Given the digit string code, return the number of ways to split it into pieces that are each a letter number from 1 to 26. A piece can't start with 0, so "06" is not a letter, and "0" alone is not a letter.

  • 1 <= len(code) <= 1000, only the characters 0 to 9.
  • The count can be huge, so return it modulo 1,000,000,007.

Examples:

count_decodings("226") → 3 (2 2 6, 22 6, 2 26)

count_decodings("06") → 0

Hints

  • Look at how the message could end: with a one-digit piece or a two-digit piece.
  • A one-digit piece is fine unless it is 0. A two-digit piece is fine only from 10 to 26.
  • The empty prefix can be read in exactly one way. Take the modulo every time you add.

Learn the pattern first: the 1-D Dynamic Programming lesson.

More 1-D Dynamic Programming problems