Decode Ways

Medium

Topics
StringDynamic Programming

A message of digits is encoded to letters using the mapping 'A' -> 1, ..., 'Z' -> 26. Given a digit string s, return the number of ways to decode it. The answer fits in a 32-bit integer.

Example 1

s12
reads asABL
Digits map to letters as A=1 … Z=26, and the string is grouped into one- or two-digit pieces. Each chip is one grouping that decodes cleanly; the answer counts them, 2. The groupings that fail are the content here: a 0 stands for no letter, and a pair above 26 is not a letter either.
Below the string, every valid way of reading it.
Input:  s = "12"
Output: 2
Explanation: "AB" (1 2) or "L" (12).

Example 2

s226
reads asBBFBZVF
Input:  s = "226"
Output: 3

Example 3

s06
reads asnothing
Input:  s = "06"
Output: 0

Constraints

  • 1 <= s.length <= 100
  • s contains only digits and may contain leading zeros.
Editorial — intuition, approach, complexity and pitfalls

Intuition

At each position you either decode one digit (1-9) or two digits (10-26). So the ways to decode up to position i is the sum of the ways ending with a valid single and a valid double.

Approach

  1. dp[0] = 1 (empty), dp[1] = 1 if s[0] != "0".
  2. For each i, add dp[i-1] if the single digit s[i-1] is 1-9.
  3. Add dp[i-2] if the two-digit s[i-2:i] is between 10 and 26.

Dry Run

s = "226"
dp[i] = number of ways to decode the first i characters. dp[0] = 1 for the empty
prefix and dp[1] = 1 for the first digit, which the leading-zero guard has
already established is decodable.
  i=2   "2" alone   -> += dp[1] = 1
        "22" as a pair (10..26) -> += dp[0] = 1       dp[2] = 2
  i=3   "6" alone   -> += dp[2] = 2
        "26" as a pair (10..26) -> += dp[1] = 1       dp[3] = 3
answer 3   --  2 2 6, 22 6, 2 26
This is Fibonacci with two conditions on the steps. The one-digit step is blocked
by a '0'; the two-digit step is blocked outside 10..26. Both blocked means dp[i]
stays 0, and because every later value reads it, the whole suffix becomes
undecodable -- which is how an illegal zero poisons the answer rather than raising
an error.
The zero cases are worth running:
  "12"  -> 2      "06"  -> 0    leading zero, rejected up front
  "10"  -> 1      the 0 only survives as part of "10"
  "27"  -> 1      "2" then "7"; 27 is out of range
  "100" -> 0      "10" then a bare "0" -- nothing can absorb it
  "230" -> 0      "2" "3" then a bare "0"; 30 is out of range too

Complexity

  • Time — O(n): one pass over the string.
  • Space — O(n): the dp array (reducible to O(1)).

Common Pitfalls

  • A "0" is only decodable as part of 10 or 20; a standalone or ill-placed 0 makes that prefix undecodable.

Full Solution — all languages

class Solution:
    def numDecodings(self, s):
        if not s or s[0]=='0': return 0
        n=len(s)
        dp=[0]*(n+1)
        dp[0]=dp[1]=1
        for i in range(2,n+1):
            if s[i-1]!='0':
                dp[i]+=dp[i-1]
            two=int(s[i-2:i])
            if 10<=two<=26:
                dp[i]+=dp[i-2]
        return dp[n]
SensAI
Beta
Tap the mic to stop voice mode