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 Problem: "226" → Multiple Decodings"226""2"+"2"+"6""2"+"26""22"+"6"B + B + FB + ZV + FTotal Ways: 3Each valid split creates a different decoded message
Understanding the Visualization
1
Input
String of digits like "226"
2
Process
Find all valid ways to split into 1-26 ranges
3
Output
Count of valid decodings
Key Takeaway
🎯 Key Insight: At each position, we can take 1 digit (1-9) or 2 digits (10-26), building solutions incrementally
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