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.
1var numDecodings = function(s) {
2 if (!s || s[0] === '0') return 0;
3 let n = s.length;
4 let dp = Array(n + 1).fill(0);
5 dp[0] = 1;
6 dp[1] = 1;
7
8 for (let i = 2; i <= n; i++) {
9 let oneDigit = parseInt(s.substring(i - 1, i));
10 let twoDigits = parseInt(s.substring(i - 2, i));
11
12 if (oneDigit >= 1) {
13 dp[i] += dp[i - 1];
14 }
15 if (twoDigits >= 10 && twoDigits <= 26) {
16 dp[i] += dp[i - 2];
17 }
18 }
19 return dp[n];
20};
JavaScript's solution leverages arrays, slice operations, and parseInt for character manipulation, considering single and two-character possibilities sequentially.
It manages an array similarly to establish counts of valid decodings observed at any index level.
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.