
Sponsored
Sponsored
This approach utilizes dynamic programming along with a frequency table to keep track of the count of each character at each column index across the given words. We calculate ways to form the target string by building up solutions to subproblems of forming prefixes of the target string using the letter frequency information efficiently.
Time Complexity: O(n*m + m*t), where n is the number of words, m is the length of each word, and t is the length of the target string.
Space Complexity: O(m*t).
1var numWays = function(words, target) {
2 const MOD = 1e9 + 7;
3 const m = words[0].length, t = target.length;
4 const dp = Array.from({ length: t + 1 }, () => Array(m + 1).fill(0));
5 const count = Array.from({ length: m }, () => Array(26).fill(0));
6
7 for (let word of words) {
8 for (let i = 0; i < m; ++i) {
9 count[i][word.charCodeAt(i) - 'a'.charCodeAt(0)]++;
10 }
11 }
12
13 for (let j = 0; j <= m; ++j) {
14 dp[0][j] = 1;
15 }
16
17 for (let i = 1; i <= t; ++i) {
18 for (let j = 1; j <= m; ++j) {
19 dp[i][j] = dp[i][j - 1];
20 const charIndex = target.charCodeAt(i - 1) - 'a'.charCodeAt(0);
21 if (count[j - 1][charIndex] > 0) {
22 dp[i][j] = (dp[i][j] + dp[i - 1][j - 1] * count[j - 1][charIndex]) % MOD;
23 }
24 }
25 }
26
27 return dp[t][m];
28};
29The JavaScript solution follows the same dynamic programming principle. It computes, using a 2D array, how the target string can be constructed from the word list by leveraging a character occurrence map, ensuring optimum time and space complexity.
This approach uses memoization to optimize the recursion while forming the target. We compute ways from each index of target and position of words and save computed results to avoid redundant calculations. This approach is effective in reducing the exponential time complexity without deep overlapping subproblems.
Time Complexity: O(n*m + m*t), optimized with memoization.
Space Complexity: O(m*t).
This solution employs a recursive depth-first search (`dfs`) with memoization. The function `dfs(i, j)` returns the number of ways to form the target string starting from index `i` of the target and index `j` of a word in `words`. The memoized `dp` array stores results of overlapping subproblems to avoid recalculations.