CodingNodes / 1-D Dynamic Programming / Decode Ways System design Space play · ←→ step · R restart

Problem

A message of letters was turned into digits using A = 1, B = 2, ..., Z = 26. Given the digit string s, count how many different letter messages it could have come from.

A letter uses one or two digits, and a letter's digits never start with 0. Return the number of ways, or 0 if the string cannot be decoded at all.

Constraints

  • 1 ≤ s.length ≤ 12
  • s has only digits

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(n)

Time: Each digit is checked with two constant-size choices.

Space: The dp array holds n + 1 counts.

dp[i] counts the decodings of the first i digits. The last letter is either one digit (valid if it is not 0), which adds dp[i-1], or two digits (valid if they form 10 to 26), which adds dp[i-2].