LeetCode #91 Medium

Decode Ways

Decode Ways is LeetCode 91 (Medium). A message of capital letters was encoded as digits with A → 1, B → 2, …, Z → 26. Given the digit string s, return the number of ways to decode it back into letters.

  • 0 maps to no letter, so it can only be read as the second digit of 10 or 20.
  • A two-digit code cannot start with 0: 06 is not the letter for 6.
  • Return 0 if no decoding exists. s has up to 100 digits, and the answer fits in a 32-bit integer.
Constraints
  • 1 <= s.length <= 100
  • s contains only digits and may contain leading zero(s).
dynamic-programmingstring
Open on LeetCode ↗
02

Intuition

Look at how the last letter of a decoding was made. It used either the last digit alone or the last two digits together. So the ways to decode the first i + 1 digits are:

  • the ways for the first i digits, if digit i is 1 to 9, plus
  • the ways for the first i − 1 digits, if digits i − 1 and i read 10 to 26.

No decoding is counted twice, because the two groups differ in the length of their last code. Each count needs only the two counts before it, so two variables are enough instead of a table.

How to spot this pattern

Counting the ways to split a sequence into pieces of length 1 or 2, where each piece has its own validity rule. The count at each position depends only on the two positions before it.

03

Approach

Try it first

Before reading on, decide what the count for the first i + 1 digits depends on. Then list exactly when a single digit and when a pair of digits can be a letter. Aim for O(n) time and O(1) space.

1

Reject a leading zero

If s[0] is '0', return 0. No letter's code starts with 0, so the first digit cannot be read at all, and no later digit can repair that.

2

Start with one way for the empty prefix and for the first digit

Set two_back = 1 and one_back = 1. The empty prefix has exactly one decoding, the empty message, which is what lets a valid first pair such as 26 add its own way.

3

Add the one-digit and the two-digit choice

For each i from 1, start here at 0. Add one_back if s[i] is not '0', and add two_back if s[i-1:i+1] is between 10 and 26. The range check rejects both 27 and 06.

4

Shift the two counts forward

Set two_back, one_back = one_back, here and move on. If here is 0, no decoding of this prefix exists, and every later count stays 0, so a zero that cannot pair, as in 30, ends with an answer of 0.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def numDecodings(self, s: str) -> int:
▶3 if s[0] == "0":
▶4 return 0
▶5 two_back, one_back = 1, 1
▶6 for i in range(1, len(s)):
▶7 here = 0
▶8 if s[i] != "0":
▶9 here += one_back
▶10 if 10 <= int(s[i - 1 : i + 1]) <= 26:
▶11 here += two_back
▶12 two_back, one_back = one_back, here
▶13 return one_back
202162→ B1two backways for “”1one backways for “2”herenext prefixfirst digit 2 → B: 1 way so far
two_back1
one_back1
The empty prefix has exactly one decoding, the empty message, and the first digit 2 can only be read as B. Both counts start at 1.
202162→ B1two backways for “”1one backways for “2”1hereways for “22”2 alone is B → add 1 way
s[i]'2'
here1
Ending with the letter B leaves “2” to decode, which has 1 way. Each of them gets B added at the end.
202162→ V1two backways for “”1one backways for “2”2hereways for “22”22 is V → add 1: “22” has 2
pair22
here2
Reading 22 as V leaves “”, with 1 way. “22” has 1 + 1 = 2 decodings; the counts now move one digit right.
202162→ F1two backways for “2”2one backways for “22”2hereways for “226”6 alone is F → add 2 ways
s[i]'6'
here2
Ending with the letter F leaves “22” to decode, which has 2 ways. Each of them gets F added at the end.
202162→ Z1two backways for “2”2one backways for “22”3hereways for “226”26 is Z → add 1: “226” has 3
pair26
here3
Reading 26 as Z leaves “2”, with 1 way. “226” has 2 + 1 = 3 decodings; the counts now move one digit right.
2021623answerways for “226”answer: 3 ways
answer3
The last count covers the whole string, so “226” decodes in 3 ways.
05

Common pitfalls

Checking only the upper bound of a pair

✗ Wrong
if int(s[i - 1 : i + 1]) <= 26:
✓ Right
if 10 <= int(s[i - 1 : i + 1]) <= 26:

A pair that starts with 0, such as 06, has a value below 10 and is not a letter code. On "106" the only decoding is 10, 6, so the answer is 1, but the bug also accepts 06 and returns 2.

Letting a 0 stand alone

✗ Wrong
here += one_back
✓ Right
if s[i] != "0":
    here += one_back

No letter has the code 0, so a single 0 adds no ways. On "10" the answer is 1 (just J), but without the check the lone 0 adds a second, impossible decoding.

Recursing without remembering results

✗ Wrong
def ways(i):
    ...
    return ways(i + 1) + ways(i + 2)
✓ Right
keep only the last two counts, or memoize ways(i)

The same suffix is solved again and again, so the number of calls grows like the answer itself. A string of 45 ones has about 1.8 · 10⁹ decodings, still inside 32 bits, and plain recursion makes about that many calls.

06

Edge cases

A zero inside the string, as in "2101"

At the 0, the single digit adds nothing and only the pair 10 counts, so here equals two_back. The answer is 1 (2, 10, 1).

07

Complexity

Time
O(n)
Space
O(1)
One pass over the string with a constant amount of work per digit. Only two_back, one_back and here are stored; a full table of n + 1 counts would make it O(n) space.
08

Decode Ways FAQ

Why does the count look like Fibonacci?

When every single digit and every pair is valid, as in "1111", each count is the sum of the two before it, which is exactly the Fibonacci rule: 1, 2, 3, 5. Zeros and pairs above 26 remove one of the two terms, which is what breaks the pattern.

What changes when the string can contain *?

Decode Ways II (LeetCode 639) allows it: a * can stand for any digit from 1 to 9. The same two choices apply, but each one is multiplied by how many digits or pairs the * could form, and the answer is taken modulo 10⁹ + 7.