Decode Ways II - Problem
Imagine you're a secret agent who needs to decode encrypted messages! ๐ต๏ธโโ๏ธ
You have a special cipher where letters A-Z are mapped to numbers:
'A' โ "1"'B' โ "2"...'Z' โ "26"
But here's the twist: the encoded message might contain wildcard characters '*' that can represent any digit from 1 to 9 (not 0)!
Example: The string "1*" could represent "11", "12", "13", ..., "19" - that's 9 different possibilities!
Your mission: Given an encoded string s with digits and '*' characters, determine how many different ways you can decode it back into letters.
Important rules:
- Leading zeros are invalid ("06" โ "6")
- Only numbers 1-26 can be decoded to letters
- Return the answer modulo 109 + 7
Input & Output
example_1.py โ Basic Wildcard
$
Input:
s = "*"
โบ
Output:
9
๐ก Note:
The wildcard '*' can represent any digit from 1-9, and each digit (1-9) corresponds to a valid letter (A-I), so there are 9 different ways to decode it.
example_2.py โ Wildcard with Digit
$
Input:
s = "1*"
โบ
Output:
18
๐ก Note:
We can decode this as: (1) Single digits: '1' + any of '1'-'9' = 1ร9 = 9 ways. (2) Two digits: '1*' can be '11'-'19' = 9 ways. Total: 9 + 9 = 18 ways.
example_3.py โ Multiple Wildcards
$
Input:
s = "2*"
โบ
Output:
15
๐ก Note:
Single digits: '2' + any of '1'-'9' = 1ร9 = 9 ways. Two digits: '2*' can be '21'-'26' (only 6 valid combinations since 27-29 > 26) = 6 ways. Total: 9 + 6 = 15 ways.
Visualization
Tap to expand
Understanding the Visualization
1
Setup Decoder
Initialize our decoder with base case: empty string has 1 way to decode
2
Handle First Character
If it's *, we have 9 ways (1-9). If it's a digit โ 0, we have 1 way
3
Process Each Position
For each new character, consider single-digit and two-digit decodings
4
Count Wildcard Possibilities
Multiply by valid digit combinations the wildcard can represent
5
Build Solution
Accumulate results in DP table, handling modular arithmetic
Key Takeaway
๐ฏ Key Insight: Dynamic Programming allows us to efficiently count all decoding possibilities by building solutions incrementally, handling wildcards by multiplying by their valid digit count at each step.
Time & Space Complexity
Time Complexity
O(n)
Single pass through the string, constant work per position
โ Linear Growth
Space Complexity
O(n)
DP array of size n+1 to store intermediate results
โก Linearithmic Space
Constraints
- 1 โค s.length โค 105
- s[i] is a digit or '*'
- No leading zeros in valid decodings
- Answer should be returned modulo 109 + 7
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code