The dynamic programming approach leverages the fact that a problem can be broken into subproblems. Here, we use an array dp where dp[i] represents the number of ways to decode the substring s[0..i-1].
We iterate through the string and update the dp array based on the valid single and two-digit mappings.
Time Complexity: O(n)
, where n is the length of the input string. This is because we iterate over each character once.
Space Complexity: O(n)
, as we use an additional array of size n for storing our results for subproblems.
1class Solution:
2 def numDecodings(self, s: str) -> int:
3 if not s or s[0] == '0':
4 return 0
5
6 n = len(s)
7 dp = [0] * (n + 1)
8 dp[0] = dp[1] = 1
9
10 for i in range(2, n + 1):
11 one_digit = int(s[i - 1:i])
12 two_digits = int(s[i - 2:i])
13
14 if 1 <= one_digit <= 9:
15 dp[i] += dp[i - 1]
16 if 10 <= two_digits <= 26:
17 dp[i] += dp[i - 2]
18
19 return dp[n]
In Python, slicing and conversion to integer make it easy to work with substrings while dynamically updating the number of decoding ways.
The use of arrays is straightforward and supports clearer indexing using Python's dynamic typing system.
Instead of using an entire array to store all previous results, this approach keeps track of only the last two computations (since we only ever need the last two values for our dp computations).
Thus, we use two variables to hold these values and update them as needed to keep our space usage minimal.
Time Complexity: O(n)
, since each character in the string is touched once.
Space Complexity: O(1)
, because only two variables are used to maintain state.
1#include <string.h>
2
3int numDecodings(char * s) {
4 if (s[0] == '0') return 0;
5 int n = strlen(s), prev2 = 1, prev1 = 1;
6
7 for (int i = 2; i <= n; i++) {
8 int current = 0;
9 int oneDigit = s[i - 1] - '0';
10 int twoDigits = (s[i - 2] - '0') * 10 + oneDigit;
11
12 if (oneDigit >= 1) {
13 current += prev1;
14 }
15 if (twoDigits >= 10 && twoDigits <= 26) {
16 current += prev2;
17 }
18 prev2 = prev1;
19 prev1 = current;
20 }
21 return prev1;
22}
This C solution reduces space complexity by using two variables - prev1
and prev2
to keep track of decodings without maintaining a full dp array.
These variables capture prior computations needed for the current index advance.