834. Decodings With Wildcards

Hard7.5 points estimatedStringDynamic Programming4 hints

A message in a toy cipher maps the letters A to Z to the numbers 1 to 26 and is transmitted as a string of digits. A damaged channel may replace any digit from 1 to 9 by the wildcard *, which stands for one of those nine digits (never 0). A group such as 06 with a leading zero is not a valid code, and 0 alone is invalid.

Given the received string s, made of digits and *, return the number of different ways to cut it into groups of one or two characters that each decode to a letter, counting every way the wildcards can be filled. Return the result modulo 1000000007, and 0 when no decoding exists. Aim for time O(n) and constant extra space.

Example 1

Input:
s = "3*4"
Output:
11
Explanation:

Reading every character alone gives 9 decodings; the pair *4 can also be 14 or 24, adding 2, so the total is 11.

Example 2

Input:
s = "*6"
Output:
11
Explanation:

The wildcard alone gives 9 readings; as a pair with 6 it can be 1 or 2, giving 2 more, for 11 in total.

Example 3

Input:
s = "1*2*"
Output:
288
Explanation:

Counting every digit and pair combination gives 288 decodings.

Constraints

1 ≤ s.length ≤ 105

s consists of the digits 0-9 and the character *.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 600 msC++ 150 msJava 300 msJavaScript 300 msTypeScript 300 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…