#639
Decode Ways II
HardStringDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses dynamic programming to store the number of ways to decode the string up to each index. This avoids redundant calculations by building on previously computed results, making it efficient.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a dp array where dp[i] represents the number of ways to decode the substring up to index i.
- 2Step 2: Set dp[0] to 1 (an empty string has one way to decode).
- 3Step 3: Iterate through the string and update dp[i] based on the current character and the previous character, considering '*' appropriately.
solution.py19 lines
1def numDecodings(s):
2 MOD = 10**9 + 7
3 n = len(s)
4 dp = [0] * (n + 1)
5 dp[0] = 1
6 for i in range(1, n + 1):
7 if s[i - 1] == '*':
8 dp[i] = (dp[i - 1] * 9) % MOD
9 else:
10 dp[i] = dp[i - 1] if s[i - 1] != '0' else 0
11 if i > 1:
12 if s[i - 2] == '*':
13 if s[i - 1] <= '6':
14 dp[i] = (dp[i] + dp[i - 2] * 2) % MOD
15 else:
16 dp[i] = (dp[i] + dp[i - 2]) % MOD
17 elif 10 <= int(s[i - 2:i]) <= 26:
18 dp[i] = (dp[i] + dp[i - 2]) % MOD
19 return dp[n]ℹ
Complexity note: The time complexity is O(n) because we iterate through the string once, and the space complexity is O(n) due to the dp array storing results for each index.
- 1Handling '*' properly is crucial as it can represent multiple digits.
- 2Dynamic programming allows us to build solutions incrementally and avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.