
Problem
Solution
Submissions
Decode Ways
Certification: Intermediate Level
Accuracy: 0%
Submissions: 0
Points: 10
Write a JavaScript program to count the number of ways to decode a string of digits. A message containing letters from A-Z can be encoded into numbers using the mapping A=1, B=2, ..., Z=26. Given a string containing only digits, determine the total number of ways to decode it back to letters.
Example 1
- Input: s = "12"
- Output: 2
- Explanation:
- The string "12" can be decoded in multiple ways.
- First way: "12" can be decoded as "1" + "2" which gives "AB".
- Second way: "12" can be decoded as "12" which gives "L".
- Both decodings are valid since 1→A, 2→B, and 12→L are all valid mappings.
- Therefore, there are 2 total ways to decode the string.
- The string "12" can be decoded in multiple ways.
Example 2
- Input: s = "226"
- Output: 3
- Explanation:
- The string "226" has multiple valid decoding combinations.
- First way: "2" + "2" + "6" which decodes to "BBF".
- Second way: "22" + "6" which decodes to "VF" (since 22→V).
- Third way: "2" + "26" which decodes to "BZ" (since 26→Z).
- All three combinations use valid letter mappings, so the answer is 3.
- The string "226" has multiple valid decoding combinations.
Constraints
- 1 <= s.length <= 100
- s contains only digits
- s may contain leading zeros
- Valid encodings are from "1" to "26" (A to Z)
- Return 0 if the string cannot be decoded
- Time Complexity: O(n)
- Space Complexity: O(n) for DP array, O(1) for optimized version
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use dynamic programming where dp[i] represents the number of ways to decode the first i characters
- For each position, check if single digit (1-9) and two digits (10-26) form valid decodings
- If current digit is valid (1-9), add dp[i-1] to current ways
- If current two digits form valid number (10-26), add dp[i-2] to current ways
- Handle edge cases like leading zeros and invalid digit combinations