Decode Ways

35 min · numDecodings()

A string of digits can hide several messages. 12 might be two letters, or it might be one — but a zero can't stand on its own.

Letters A through Z correspond to the strings "1" through "26". Given a non-empty digit string s, return the number of different ways to split it into valid letter codes.

A few ground rules:

  • A one-digit code is valid only from "1" through "9".
  • A two-digit code is valid only from "10" through "26".
  • A leading "0" is invalid. Elsewhere, "0" works only as part of "10" or "20".
  • Return 0 when the whole string has no valid decoding.

Constraints

  • 1 <= s.length <= 80
  • s contains only the digits 0 through 9.
  • The exact decoding count is less than 2^31.

Hints

Look at the next cut

From one position, you can consume one digit when it isn't 0. You can also consume two digits when their value lies from 10 through 26.

Name the subproblem

Let ways(i) count valid decodings of the suffix starting at index i. Its answer comes from the valid one-digit and two-digit choices, each followed by a smaller suffix.

Keep two prefix counts

When scanning left to right, the count for the current prefix reads only the previous prefix and the prefix two positions back. Roll those two values forward.

Follow-up

How would your transitions change if "*" could stand for any digit from 1 through 9?

Visible cases

Examples

Example 1

ready
Input
s = "12"
Expected
2
Why
decode as 1|2 or as 12

Example 2

ready
Input
s = "226"
Expected
3
Why
the valid splits are 2|2|6, 22|6, and 2|26

Example 3

ready
Input
s = "06"
Expected
0
Why
a code cannot begin with 0

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite