Skip to content

Commit ea0cefc

Browse files
authored
Update StringInterleaving.java
1 parent 5cdd2c2 commit ea0cefc

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

DynamicProgramming/StringInterleaving.java

+25-3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@
88
99
*/
1010

11+
//For only recursion --> Worst Case Time Complexity - O(2^(n+m)) --> When both strings are the same
12+
//n and m are lengths of the two strings
13+
1114
//MEMOIZED RECUSRION
1215
public boolean isInterleaving(String X, String Y, String S, HashMap<String, Boolean> map){
1316
if(X.length() == 0 && Y.length() == 0 && S.length() == 0) return true;
@@ -28,24 +31,43 @@ public boolean isInterleaving(String X, String Y, String S){
2831

2932
if(X.length()+Y.length() != S.length()) return false;
3033

34+
//T[i][j] indicates if S( 0....(i+j-1) ) is an interleaving of X(0...i) and Y(0...j)
3135
int T[][] = new int[X.length()+1][Y.length()+1];
3236

3337
for(int i=0 ; i < X.length() ; i++){
3438
for(int j=0 ; j < Y.length() ; j++){
39+
40+
//total length of S to be checked for interleaving when first i charachters from X and first j characters from Y are considered
41+
int l = i + j - 1;
42+
43+
//is interleaving of two empty strings also an empty string? ==> True
3544
if(i==0 && j==0) T[i][j] = true;
3645

46+
//when X is an empty string ==> Only check Y and S
3747
else if(i==0){
38-
if(Y.charAt(j-1) == S.charAt(j-1)) T[i][j] = T[i][j-1];
48+
//Check is the current characters match? ==> If True, check the subproblem ==>
49+
//==> does Y(0...j-1) form an interleaving in S(0...j-1)
50+
//solution to current problem is true only when -
51+
// 1. current characters match
52+
// 2. the subproblem also forms an interleaving ie. the subproblem returns true
53+
if(Y.charAt(j-1) == S.charAt(l)) T[i][j] = T[i][j-1];
3954
}
4055

4156
else if(j==0){
42-
if(X.charAt(i-1) == S.charAt(i-1)) T[i][j] = T[i-1][j];
57+
if(X.charAt(i-1) == S.charAt(l)) T[i][j] = T[i-1][j];
4358
}
59+
//checks if either of the current characters X[i-1] or Y[j-1] matches the current character from interleaved string S[l]
4460
else{
45-
T[i][j] = (X.charAt(i-1) == S.charAt(i-1) ? T[i-1][j] : false) || (Y.charAt(j-1) == S.charAt(j-1) ? T[i][j-1] : false);
61+
//If there is a match of current characters, solve the subproblem ie. T[i-1][j] or T[i][j-1]
62+
T[i][j] = (X.charAt(i-1) == S.charAt(l) ? T[i-1][j] : false) || (Y.charAt(j-1) == S.charAt(l) ? T[i][j-1] : false);
4663
}
4764
}
4865
}
4966

5067
return T[X.length()][Y.length()];
5168
}
69+
70+
/*
71+
Time Complexity and Space Complexity - O(X.length()*Y.length())
72+
73+
*/

0 commit comments

Comments
 (0)