MediumNo. 0091

Decode Ways — LeetCode 91 Python Solution

Topics
String, Dynamic Programming
On study lists
Blind 75 and NeetCode 150
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

PythonSolution
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

Time
O(n)
Space · auxiliary
O(n)

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

Related problems
No.ProblemDifficulty
0639Decode Ways IIHard
0087Scramble StringHard
0097Interleaving StringMedium
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard

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.

Free to download. Check it runs on your machine, then pick a plan.