Decode Ways - Problem

You have intercepted a secret message encoded as a string of numbers. The message is decoded via the following mapping:

"1" -> 'A', "2" -> 'B', ..., "25" -> 'Y', "26" -> 'Z'

However, while decoding the message, you realize that there are many different ways you can decode the message because some codes are contained in other codes ("2" and "5" vs "25").

For example, "11106" can be decoded into:

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

The grouping (1, 11, 06) is invalid because "06" is not a valid code (only "6" is valid).

Note: There may be strings that are impossible to decode.

Given a string s containing only digits, return the number of ways to decode it. If the entire string cannot be decoded in any valid way, return 0.

Input & Output

Example 1 — Basic Case
$ Input: s = "12"
Output: 2
💡 Note: Two ways to decode: "1"+"2" → AB, or "12" → L. Both are valid decodings.
Example 2 — Multiple Options
$ Input: s = "226"
Output: 3
💡 Note: Three ways: "2"+"2"+"6" → BBF, "2"+"26" → BZ, "22"+"6" → VF. All valid decodings.
Example 3 — Leading Zero
$ Input: s = "06"
Output: 0
💡 Note: Cannot decode because "06" is invalid (leading zero) and "0" alone is invalid. No valid decodings.

Constraints

  • 1 ≤ s.length ≤ 100
  • s contains only digits
  • s may have leading zeros

Visualization

Tap to expand
Decode Ways - Space-Optimized DP INPUT String s = "12" 1 idx 0 2 idx 1 Mapping: "1" --> 'A' "2" --> 'B' ... "12" --> 'L' ... "26" --> 'Z' Possible: "AB" or "L" (1,2) or (12) ALGORITHM STEPS 1 Initialize DP vars prev2=1, prev1=1 2 Check single digit If s[i]!='0': curr+=prev1 3 Check two digits If 10-26: curr+=prev2 4 Update variables prev2=prev1, prev1=curr Iteration for i=1 (s[1]='2'): prev2 = 1, prev1 = 1 s[1]='2' != '0' --> curr=1 "12" in [10,26] --> curr+=1 curr = 2 Update: prev1 = 2 FINAL RESULT Number of decode ways: 2 Valid Decodings: "1" + "2" --> "AB" A (1) + B (2) "12" --> "L" L (12) Output: 2 [OK] Key Insight: Space-Optimized DP uses only 2 variables (prev1, prev2) instead of full array. At each position, ways = (single digit valid ? prev1 : 0) + (two digits valid ? prev2 : 0) Time: O(n) | Space: O(1) - Only tracking previous two states needed for transition. TutorialsPoint - Decode Ways | Space-Optimized DP Approach
Asked in
Facebook 45 Microsoft 38 Google 32 Amazon 28
89.3K Views
High Frequency
~25 min Avg. Time
2.8K 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