Decode Ways - Problem
Secret Agent Decoder Challenge!
You're a secret agent who has intercepted an encrypted message consisting only of
However, there's a twist! ๐ต๏ธ The same encoded string can often be decoded in multiple different ways because some codes overlap. For example:
โข The string
โข The string
Important rules:
โข Only numbers 1-26 are valid codes
โข Leading zeros make a code invalid ("06" is invalid, but "6" is valid)
โข If no valid decoding exists, return 0
Goal: Count the total number of different ways to decode the given string.
You're a secret agent who has intercepted an encrypted message consisting only of
digits. The encryption follows a simple pattern where numbers map to letters: "1" โ 'A', "2" โ 'B', ..., "26" โ 'Z'.However, there's a twist! ๐ต๏ธ The same encoded string can often be decoded in multiple different ways because some codes overlap. For example:
โข The string
"12" could be decoded as "AB" (1โA, 2โB) or as "L" (12โL)โข The string
"226" has 3 ways: "BBF" (2,2,6), "BZ" (2,26), or "VF" (22,6)Important rules:
โข Only numbers 1-26 are valid codes
โข Leading zeros make a code invalid ("06" is invalid, but "6" is valid)
โข If no valid decoding exists, return 0
Goal: Count the total number of different ways to decode the given string.
Input & Output
example_1.py โ Basic case
$
Input:
"12"
โบ
Output:
2
๐ก Note:
Two ways to decode: "AB" (1,2) or "L" (12). Both are valid since 1โค12โค26.
example_2.py โ Multiple possibilities
$
Input:
"226"
โบ
Output:
3
๐ก Note:
Three ways: "BBF" (2,2,6), "BZ" (2,26), or "VF" (22,6). All combinations form valid letter codes.
example_3.py โ Invalid zero case
$
Input:
"06"
โบ
Output:
0
๐ก Note:
No valid decoding exists. "06" is invalid due to leading zero, and we can't decode an empty first part.
Visualization
Tap to expand
Understanding the Visualization
1
Start with blocks
Each digit is a potential block of size 1, pairs of digits are blocks of size 2
2
Check validity
Single blocks (1-9) are always valid, double blocks (10-26) are sometimes valid
3
Count combinations
Use DP to count all valid ways to combine blocks to build the complete structure
4
Build solution
Each position's count = ways using single block + ways using double block
Key Takeaway
๐ฏ Key Insight: This problem has optimal substructure - the number of ways to decode any position depends only on the ways to decode the next 1-2 positions, making it perfect for dynamic programming!
Time & Space Complexity
Time Complexity
O(n)
Each position is computed only once and cached, so we do O(n) work total
โ Linear Growth
Space Complexity
O(n)
Memoization table stores results for up to n different positions, plus recursion stack
โก Linearithmic Space
Constraints
- 1 โค s.length โค 100
- s contains only digits
- s may contain leading zero(s)
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code