|
| 1 | +--- |
| 2 | +title: Leetcode 91. Decode Ways |
| 3 | +description: Explanation for Leetcode 91 - Decode Ways, and its solution in Python. |
| 4 | +date: 2025-05-09 |
| 5 | +categories: [Leetcode, Dynamic Programming, Medium] |
| 6 | +tags: [Leetcode, Python, Dynamic Programming, Medium] |
| 7 | +math: true |
| 8 | +--- |
| 9 | + |
| 10 | +## Problem |
| 11 | +[Leetcode 91 - Decode Ways](https://leetcode.com/problems/decode-ways/description/) |
| 12 | + |
| 13 | +Example: |
| 14 | +``` |
| 15 | +Input: s = "12" |
| 16 | +Output: 2 |
| 17 | +Explanation: It can be decoded as "AB" (1 2) or "L" (12). |
| 18 | +
|
| 19 | +Input: s = "226" |
| 20 | +Output: 3 |
| 21 | +Explanation: It can be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). |
| 22 | +
|
| 23 | +Input: s = "06" |
| 24 | +Output: 0 |
| 25 | +Explanation: "06" cannot be mapped to any letter. |
| 26 | +``` |
| 27 | + |
| 28 | +## Approach |
| 29 | + |
| 30 | +We can solve this problem using Dynamic Programming. The idea is to use a DP array where `dp[i]` represents the number of ways to decode the substring `s[:i]`. We iterate through the string and update the DP array based on valid single-digit and two-digit decodings. |
| 31 | + |
| 32 | +Here is the Python code for the solution: |
| 33 | +```python |
| 34 | +class Solution: |
| 35 | + def numDecodings(self, s: str) -> int: |
| 36 | + if not s or s[0] == '0': |
| 37 | + return 0 |
| 38 | + |
| 39 | + n = len(s) |
| 40 | + dp = [0] * (n + 1) |
| 41 | + dp[0] = 1 # Base case: empty string has one way to decode |
| 42 | + dp[1] = 1 # Base case: single character (non-zero) has one way to decode |
| 43 | + |
| 44 | + for i in range(2, n + 1): |
| 45 | + # Check single-digit decoding |
| 46 | + if s[i - 1] != '0': |
| 47 | + dp[i] += dp[i - 1] |
| 48 | + |
| 49 | + # Check two-digit decoding |
| 50 | + two_digit = int(s[i - 2:i]) |
| 51 | + if 10 <= two_digit <= 26: |
| 52 | + dp[i] += dp[i - 2] |
| 53 | + |
| 54 | + return dp[n] |
| 55 | +``` |
| 56 | + |
| 57 | +## Time Complexity and Space Complexity |
| 58 | + |
| 59 | +Time Complexity: $O(n)$ |
| 60 | + |
| 61 | +Space Complexity: $O(n)$ |
0 commit comments