Decode Ways — LeetCode 91 Python Solution
- Problem
- #91
- Pattern
- Dynamic Programming
- 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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.