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 - Space-Optimized DP INPUT * Character Mapping: A=1 B=2 ... Z=26 Wildcard '*' represents: 1, 2, 3, 4, 5, 6, 7, 8, 9 Input String: s = "*" ALGORITHM STEPS 1 Initialize DP prev2=1, prev1=0 2 Single Digit Check '*' can be 1-9 (9 ways) 3 Two Digit Check No prev char, skip 4 Update DP Values curr = 9 * prev2 = 9 Space-Optimized DP: prev2 1 prev1 0 curr 9 curr = 9 * 1 + 0 = 9 mod (10^9 + 7) FINAL RESULT '*' can decode to: 1 A 2 B 3 C 4 D 5 E 6 F 7 G 8 H 9 I Output: 9 OK - 9 decode ways Key Insight: Space-optimized DP uses only O(1) space by tracking just prev2 and prev1 values instead of full array. For '*', count single digit ways (9 for 1-9) and two digit ways based on previous character. TutorialsPoint - Decode Ways II | Space-Optimized DP Approach
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