




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.
1public class Solution {
2    public bool IsInterleave(string s1, string s2, string s3) {
3        int n = s1.Length;
4        int m = s2.Length;
5        int l = s3.Length;
6        if (n + m != l) return false;
7        bool[,] dp = new bool[n + 1, m + 1];
8        dp[0, 0] = true;
9        for (int i = 0; i <= n; i++) {
10            for (int j = 0; j <= m; j++) {
11                if (i > 0) {
12                    dp[i, j] = dp[i, j] || (dp[i - 1, j] && s1[i - 1] == s3[i + j - 1]);
13                }
14                if (j > 0) {
15                    dp[i, j] = dp[i, j] || (dp[i, j - 1] && s2[j - 1] == s3[i + j - 1]);
16                }
17            }
18        }
19        return dp[n, m];
20    }
21}The C# solution also follows a dynamic programming approach, using a 2D dp array to record if s3 up to index i+j can be formed from s1 and s2. Each step checks inclusion of a character from either string.
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.