Decode Ways — LeetCode 91 Python Solution

MediumStringDynamic Programming
Problem
#91
Reading time
2 min

The 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' ...

Python solution

Python
class Solution:
    def numDecodings(self, s: str) -> int:
        n = len(s)
        f = [1] + [0] * n
        for i, c in enumerate(s, 1):
            if c != "0":
                f[i] = f[i - 1]
            if i > 1 and s[i - 2] != "0" and int(s[i - 2 : i]) <= 26:
                f[i] += f[i - 2]
        return f[n]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 91. Decode Ways is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On study lists

This problem is on Blind 75 and NeetCode 150.

Frequently asked questions

How hard is LeetCode 91. Decode Ways?
LeetCode 91. Decode Ways is rated Medium on LeetCode.
What is the time complexity of LeetCode 91. Decode Ways?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 91. Decode Ways?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 91. Decode Ways cover?
LeetCode 91. Decode Ways is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview