MediumNo. 0091
Decode Ways — LeetCode 91 Python Solution
- Pattern
- Dynamic Programming
- Topics
- String, Dynamic Programming
- On study lists
- Blind 75 and NeetCode 150
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| No. | Problem | Difficulty |
|---|---|---|
| 0639 | Decode Ways II | Hard |
| 0087 | Scramble String | Hard |
| 0097 | Interleaving String | Medium |
| 0010 | Regular Expression Matching | Hard |
| 0022 | Generate Parentheses | Medium |
| 0032 | Longest Valid Parentheses | Hard |
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.