




Sponsored
Sponsored
This approach uses a dynamic programming table to ascertain whether the third string, s3, is an interleaving of s1 and s2. We use a 2D DP array dp[i][j] which signifies if s3[0:i+j] is an interleaving of s1[0:i] and s2[0:j]. A bottom-up approach is taken to fill this table.
Time Complexity: O(n * m), where n and m are the lengths of s1 and s2, respectively.
Space Complexity: O(n * m), required for the dp array.
1var isInterleave = function(s1, s2, s3) {
2    const n = s1.length;
3    const m = s2.length;
4    const l = s3.length;
5    if (n + m !== l) return false;
6    const dp = Array.from({ length: n + 1 }, () => Array(m + 1).fill(false));
7    dp[0][0] = true;
8    for (let i = 0; i <= n; i++) {
9        for (let j = 0; j <= m; j++) {
10            if (i > 0) {
11                dp[i][j] = dp[i][j] || (dp[i - 1][j] && s1[i - 1] === s3[i + j - 1]);
12            }
13            if (j > 0) {
14                dp[i][j] = dp[i][j] || (dp[i][j - 1] && s2[j - 1] === s3[i + j - 1]);
15            }
16        }
17    }
18    return dp[n][m];
19};The JavaScript solution follows the same DP logic using a 2D array. It tracks whether each prefix of s3 can be formed by interleaving prefixes of s1 and s2.
This recursive approach tries to construct the interleaved string by attempting to use characters from s1 and s2 to match each character of s3. To optimize, memoization is applied to avoid recalculating results for the same subproblems.
Time Complexity: O(n * m), due to memoization allowing only one calculation per subproblem.
Space Complexity: O(n * m) for the memoization table.
1
We define recursiveMemo which explores the subproblems of forming s3 using portions of s1 and s2. The results of subproblems are stored in memo, providing efficiency by not recalculating results.