Skip to content

Decode Ways

Count the ways to turn a string of digits back into letters, where 1 is A and 26 is Z.

Medium1D Dynamic Programming
Solve on LeetCode

The problem

A message of capital letters was written as numbers with A = 1, B = 2, up to Z = 26, and the numbers were joined into the digit string s. Return the number of ways to split s back into letters, where every piece is a number from 1 to 26 with no leading zero. Return 0 if no split works, and you can assume the answer fits in a 32-bit integer.

Input s = "1126"

Output 5

The splits are 1 1 2 6, 11 2 6, 1 12 6, 1 1 26 and 11 26.

Input s = "2101"

Output 1

The 0 must pair with the 1 before it as 10, so the only split is 2 10 1.

Key constraint: A 0 can never stand alone; it is only valid as the second digit of 10 or 20.

How to spot the pattern

  • You count the ways to split a sequence into pieces of length 1 or 2.
  • Whether a piece is valid depends only on the last one or two characters.
  • It is Climbing Stairs with rules about which steps are allowed.

The idea

State: ways[i] is the number of ways to decode the first i characters, with ways[0] = 1 for the empty prefix. The last piece of a decoding is either the single digit s[i - 1], allowed when it is not 0, or the two digits s[i - 2] and s[i - 1], allowed when they form 10 to 26. So ways[i] adds ways[i - 1] when the first case is allowed and ways[i - 2] when the second is, and ways[n] is the answer.

Brute force: Recursively try a 1-digit and a 2-digit first piece at every position without saving results, which takes O(2^n) time.

Step by step

  1. 1Make an array ways of size n + 1 with ways[0] = 1.
  2. 2For each i from 1 to n, add ways[i - 1] to ways[i] when s[i - 1] is not '0'.
  3. 3If i >= 2 and the digits s[i - 2] and s[i - 1] form a number from 10 to 26, add ways[i - 2] as well.
  4. 4Return ways[n].

See the pattern move

The 1d dynamic programming pattern on a small example. Step through it, or press play.

Code

class Solution:
    def numDecodings(self, s: str) -> int:
        n = len(s)
        # ways[i] = ways to decode the first i characters; the empty prefix has 1 way
        ways = [0] * (n + 1)
        ways[0] = 1
        for i in range(1, n + 1):
            if s[i - 1] != "0":  # the last character alone is a letter from 1 to 9
                ways[i] += ways[i - 1]
            if i >= 2 and 10 <= int(s[i - 2:i]) <= 26:  # the last two characters form 10 to 26
                ways[i] += ways[i - 2]
        return ways[n]

Complexity

Time

O(n)

Space

O(n)

One pass over the string, with one table entry per prefix.

Watch out for

  • Letting a 0 stand alone, or accepting pieces like 05: a 0 is valid only inside 10 or 20.
  • Treating every two-digit pair as a letter: 27 and above are not.
  • Expecting a string that starts with 0 to have a decoding; its answer is 0.

Follow-up questions

Can you do it in O(1) extra space?

Yes. ways[i] only looks at ways[i - 1] and ways[i - 2], so keep those two in variables and shift them each step, as in Climbing Stairs.

What if the string could hold a * that stands for any digit from 1 to 9?

The same DP works, but a * multiplies the counts: 9 choices on its own, plus every pair with its neighbor that forms 10 to 26. That is Decode Ways II, which asks for the count modulo 10^9 + 7.

In Hinglish

Aakhri tukda ya toh ek digit hai ya do digit. Ek digit tab chalega jab woh 0 na ho, do digit tab jab 10 se 26 ke beech ho, bas dono cases ke ways jod do.

Related problems