0:00 / 0:00

Count the ways a string of digits can decode into letters. Each digit can stand alone or pair with the one before it, like climbing stairs.

▼

The problem

LeetCode 91 (Medium). Letters are encoded as numbers, A = 1, B = 2, ... Z = 26. Given a string of digits, return the number of ways to decode it (a group with a leading zero, like "06", is not a letter).

Examples (LeetCode's): "12" → 2 (AB, L), "226" → 3 (BZ, VF, BBF), "06" → 0.

TRY IT ON LEETCODE ▶

The solution

def numDecodings(s):
    two, one = 0, 1     # counts two back, one back
    for i in range(len(s)):
        cur = one if s[i] != '0' else 0
        if i > 0 and '10' <= s[i-1:i+1] <= '26':
            cur += two
        two, one = one, cur
    return one

Transcript

Decode Ways. A spy sends a secret message as digits: A is one, B is two, and so on, up to Z at twenty-six. There are no spaces between the letters. So how many ways can the digits be read back as letters?

One two reads as A B, or as L: two ways. Two two six has three: B Z, V F, or B B F. And zeros are the catch. Zero six has no reading at all: no letter is zero, and zero six isn't a letter.

The naive way tries every cut: read one digit or two off the front, then decode the rest the same way. It works, but the same tails get decoded again and again, so the calls grow exponentially.

Better: count from the left, one digit at a time. A reading can only end in two ways. If the last digit isn't zero, it's a letter on its own: add the count from one back. If the last two digits make ten to twenty-six, they're one letter: add the count from two back. It's climbing stairs, with rules.

In code, keep just two counts, starting with one way to read nothing. For each digit, take the last count if the digit isn't zero, add the one before it if the pair is ten to twenty-six, then shift both counts along.

Let's decode one one one zero six. One: one way. One one: two. One one one: three. The zero can't stand alone, but one zero is J, so the count drops to two. And zero six isn't a letter, so the six alone keeps two: A A J F, and K J F.

Each digit is checked once, so the time is order n. And only two counts are kept, not a table, so the space is order one.

One digit or two, add up the counts, and mind the zeros. That's Decode Ways.