8
8
9
9
*/
10
10
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
+
11
14
//MEMOIZED RECUSRION
12
15
public boolean isInterleaving (String X , String Y , String S , HashMap <String , Boolean > map ){
13
16
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){
28
31
29
32
if (X .length ()+Y .length () != S .length ()) return false ;
30
33
34
+ //T[i][j] indicates if S( 0....(i+j-1) ) is an interleaving of X(0...i) and Y(0...j)
31
35
int T [][] = new int [X .length ()+1 ][Y .length ()+1 ];
32
36
33
37
for (int i =0 ; i < X .length () ; i ++){
34
38
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
35
44
if (i ==0 && j ==0 ) T [i ][j ] = true ;
36
45
46
+ //when X is an empty string ==> Only check Y and S
37
47
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 ];
39
54
}
40
55
41
56
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 ];
43
58
}
59
+ //checks if either of the current characters X[i-1] or Y[j-1] matches the current character from interleaved string S[l]
44
60
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 );
46
63
}
47
64
}
48
65
}
49
66
50
67
return T [X .length ()][Y .length ()];
51
68
}
69
+
70
+ /*
71
+ Time Complexity and Space Complexity - O(X.length()*Y.length())
72
+
73
+ */
0 commit comments