Decode Ways II - Problem

A message containing letters from A-Z can be encoded into numbers using the following mapping:

'A' -> "1"
'B' -> "2"
...
'Z' -> "26"

To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways).

For example, "11106" can be mapped into:

  • "AAJF" with the grouping (1 1 10 6)
  • "KJF" with the grouping (11 10 6)

Note that the grouping (1 11 06) is invalid because "06" cannot be mapped into 'F' since "6" is different from "06".

In addition to the mapping above, an encoded message may contain the '*' character, which can represent any digit from '1' to '9' ('0' is excluded). For example, the encoded message "1*" may represent any of the encoded messages "11", "12", "13", "14", "15", "16", "17", "18", or "19". Decoding "1*" is equivalent to decoding any of the encoded messages it can represent.

Given a string s consisting of digits and '*' characters, return the number of ways to decode it. Since the answer may be very large, return it modulo 10⁹ + 7.

Input & Output

Example 1 — Basic Wildcard
$ Input: s = "*"
Output: 9
💡 Note: The * can be any digit 1-9, each giving one valid decode way: 'A' through 'I'
Example 2 — Two Digit Combinations
$ Input: s = "1*"
Output: 18
💡 Note: Can decode as: single digits '1' + '*' (1×9=9 ways), or two digits '1*' as 11-19 (9 ways). Total: 9+9=18
Example 3 — Complex Pattern
$ Input: s = "2*"
Output: 15
💡 Note: Single digits: '2' + '*' (1×9=9 ways). Two digits: '2*' as 21-26 (6 ways). Total: 9+6=15

Constraints

  • 1 ≤ s.length ≤ 105
  • s[i] is a digit or '*'
  • Answer modulo 109 + 7

Visualization

Tap to expand
Decode Ways II: Understanding WildcardsInput: "1*""1""*"A (1)B-I (2-9)"1*" as 11-19K-S (11-19)Single digit ways: 1 × 9 = 9Two digit ways: 9 (11-19)Total: 9 + 9 = 18
Understanding the Visualization
1
Input
String with digits and * wildcards
2
Process
Count all valid decode combinations
3
Output
Total number of ways modulo 10⁹+7
Key Takeaway
🎯 Key Insight: Wildcards multiply the number of valid decodings, requiring careful counting of all possibilities
Asked in
Google 45 Facebook 38 Amazon 32
32.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen