Interleaved Strings | Practice | GeeksforGeeks

Given strings A, B, and C, find whether C is formed by an interleaving of A and B.
An interleaving of two strings S and T is a configuration such that it creates a new string Y from the concatenation substrings of A and B and |Y| = |A + B| = |C|
For example:
A = "XYZ"
B = "ABC"
so we can make multiple interleaving string Y like, XYZABC, XAYBCZ, AXBYZC, XYAZBC and many more so here your task is to check whether you can create a string Y which can be equal to C.
Specifically, you just need to create substrings of string A and create substrings B and concatenate them and check whether it is equal to C or not.
Note: a + b is the concatenation of strings a and b.
Return true if C is formed by an interleaving of A and B, else return false.
Example 1:
Input:
A = YX, B = X, C = XXY
Output: 0
Explanation: XXY is not interleaving
of YX and X

Example 2:
Input:
A = XY, B = X, C = XXY
Output: 1
Explanation: XXY is interleaving of
XY and X.

Your Task:
Complete the function isInterleave() which takes three strings A, B and C as input and returns true if C is an interleaving of A and B else returns false. (1 is printed by the driver code if the returned value is true, otherwise 0.)
Expected Time Complexity: O(N * M)
Expected Auxiliary Space: O(N * M)
here, N = length of A, and M = length of B
Constraints:
1 ≤ length of A, B ≤ 100
1 ≤ length of C ≤ 200
0
milindprajapatmst191 week ago
const int N = 100;
int dp[N + 1][N + 1];

class Solution{
  public:
    /*You are required to complete this method */
    bool isInterleave(string A, string B, string C, int i = 0, int j = 0, int k = 0) {
        if (k == C.length())
            return true;
        if (dp[i][j] == -1) {
            bool result = false;
            if (A[i] == C[k])
                result |= isInterleave(A, B, C, i + 1, j, k + 1);
            if (B[j] == C[k])
                result |= isInterleave(A, B, C, i, j + 1, k + 1);
            dp[i][j] = result;
        }
        return dp[i][j];
    }
    Solution() {
        memset(dp, -1, sizeof(dp));
    }
};
0
bokonist2 weeks ago
//C++, Bottom-UP DP solution with comments. 
//time: 0.03/1.04, 
//TC: O(n*m), SC: O(n*m)

bool isInterleave(string A, string B, string C) 
    {
        //Your code here
        int n= A.length();
        int m= B.length();
        bool ** memo = new bool * [n+1]; //n+1, m+1 is to hold info when 1 string is completely traversed and other is not
        for(int i=0;i<n+1;i++)
        {
            memo[i] = new bool[m+1];
            fill(memo[i],memo[i]+m+1,false); //initialize everything to false
        }
        if(n+m != C.length()) //if the lengths dont add up, then its auto false
            return false;
        
        /*
            the dp table memo, represents the question: "At index n for A and m for B, can the rest of the string be interleaved"
        */
        memo[n][m] = true; // if both are traversed completely, its an auto true, bc theres nothing left to interleave
        for(int i=n;i>=0;i--) //build the table from bottom up
        {
            for(int j=m;j>=0;j--)
            {
                if(i==n && j==m) // base case already computed, so ignore
                    continue;
                if(i<n && A[i] == C[i+j] && memo[i+1][j]) // see if i in bounds, A[i] can be selected, and rest can be interleaved
                    memo[i][j] = true;
                else if(j<m && B[j] == C[i+j] && memo[i][j+1]) // same as above
                    memo[i][j] = true;
                else
                    memo[i][j] = false; // both above didnt meet the conditions, so its a false
            }
        }
        return memo[0][0];
    }
0
prathameshkelapure4 weeks ago
// { Driver Code Starts//Initial template for C++
#include <bits/stdc++.h>using namespace std;
// } Driver Code Ends//User function template for C++
class Solution{ public:   /*You are required to complete this method */   bool isInterleave(string a, string b, string c)    {    unordered_map<string,bool>mp;      bool ans= omma(a,b,c,mp,a.size()-1,b.size()-1,c.size()-1);      return ans;   }bool omma(string a,string b,string c,unordered_map<string,bool>&mp,int i,int j,int k){if(k<0)return 1;
string str;
str=to_string(i)+"kid"+to_string(j)+to_string(k);if(mp[str]!=0)return mp[str];
if(i<0&&j>=0){if(b[j]==c[k]){return mp[str]=omma(a,b,c,mp,i,j-1,k-1);}else{return 0;}}
if(i>=0&&j<0){if(c[k]==a[i]){return mp[str]=omma(a,b,c,mp,i-1,j,k-1);}else{return 0;}}
   
if(c[k]==a[i]&&c[k]==b[j]){return mp[str]=(omma(a,b,c,mp,i-1,j,k-1)||omma(a,b,c,mp,i,j-1,k-1));}  else if(b[j]==c[k]){return mp[str]=omma(a,b,c,mp,i,j-1,k-1);}else if(c[k]==a[i]){return mp[str]=omma(a,b,c,mp,i-1,j,k-1);}
else return 0;}
 
};
// { Driver Code Starts.int main() {int t;cin>>t;while(t--){ string a,b,c; cin>>a; cin>>b; cin>>c; Solution obj; cout<<obj.isInterleave(a,b,c)<<endl;}return 0;}  
-1
dattadroidstudy1 month ago
public boolean isInterLeave(String a,String b,String c){           //Your code here       int m = a.length();       int n = b.length();       boolean dp[][] = new boolean[m+1][n+1];       if(c.length() != (m+n))           return false;       for(int i=0;i<=m;i++){           for(int j=0;j<=n;j++){               if(i==0&&j==0){                 dp[i][j]=true;               }               else if(i==0){                 if(b.charAt(j-1)==c.charAt(j-1)){                     dp[i][j]=dp[i][j-1];                 }                 }               else if(j==0){                   if(a.charAt(i-1)==c.charAt(i-1)){                       dp[i][j]=dp[i-1][j];                   }               }               else if(a.charAt(i-1)==c.charAt(i+j-1)                && b.charAt(j-1) != c.charAt(i+j-1)){                   dp[i][j]=dp[i-1][j];               }               else if(a.charAt(i-1)!=c.charAt(i+j-1)                && b.charAt(j-1)==c.charAt(i+j-1)){                   dp[i][j]=dp[i][j-1];               }               else if(a.charAt(i-1)==c.charAt(i+j-1)                && b.charAt(j-1)==c.charAt(i+j-1)){                   dp[i][j]=(dp[i-1][j] || dp[i][j-1]);               }           }       }       return dp[m][n];}
0
ritikamalik100102
This comment was deleted.
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N*M) and space complexity as O(N*M) is as follows :- 
 
Execution Time :- 0.1 / 1.0 sec
 
int dp[101][101][201];      int helper(string a,string b,string c,int n,int m,int len){       if(len == 0) return (1);       if(n == 0 && m == 0) return (0);              if(dp[n][m][len] != -1) return (dp[n][m][len]);              int x = 0, y = 0;       if(n-1 >= 0 && a[n-1] == c[len-1]) x = helper(a,b,c,n-1,m,len-1);       if(m-1 >= 0 && b[m-1] == c[len-1]) y = helper(a,b,c,n,m-1,len-1);       if(x == 1 || y == 1) return (dp[n][m][len] = 1);       return (dp[n][m][len] = 0);   }      bool isInterleave(string A, string B, string C) {       int n = A.length();       int m = B.length();       int len = C.length();       if(n+m != len) return (false);       memset(dp,-1,sizeof(dp));       return helper(A,B,C,n,m,len) == 1 ? true : false;   }
+1
sangamchoudhary72 months ago
3D Dp
class Solution {
public:
    int dp[101][101][201];
    bool solve(int i,int j,int k,string temp,string &s1,string &s2,string &s3){
        if(i == s1.length() and j == s2.length() and k == s3.length()) 
            return temp == s3;
        else if(dp[i][j][k] != -1) 
            return dp[i][j][k];
        
        bool op1 = false,op2 = false;
        
        if(i < s1.size() and s1[i] == s3[k]) op1 = solve(i+1,j,k+1,temp + s1[i],s1,s2,s3);
        
        if(j < s2.size() and s2[j] == s3[k]) op2 = solve(i,j+1,k+1,temp + s2[j],s1,s2,s3);
        
        bool res = op1 or op2;
        return dp[i][j][k] = res;
    } 
    
    bool isInterleave(string s1, string s2, string s3){
        int n1 = s1.size(),n2=s2.size(),n3=s3.size();
        if(n1 + n2 != n3) return false;
        memset(dp,-1,sizeof dp);
        return solve(0,0,0,"",s1,s2,s3);
    }
};
 
2D DP solution - replace k with i+j everywhere
 
class Solution {
public:
    int dp[101][101];
    bool solve(int i,int j,string temp,string &s1,string &s2,string &s3){
        if(i == s1.length() and j == s2.length() and i+j == s3.length()) 
            return temp == s3;
        else if(dp[i][j] != -1) 
            return dp[i][j];
        
        bool op1 = false,op2 = false;
        
        if(i < s1.size() and s1[i] == s3[i+j]) op1 = solve(i+1,j,temp + s1[i],s1,s2,s3);
        
        if(j < s2.size() and s2[j] == s3[i+j]) op2 = solve(i,j+1,temp + s2[j],s1,s2,s3);
        
        bool res = op1 or op2;
        return dp[i][j] = res;
    } 
    
    bool isInterleave(string s1, string s2, string s3){
        int n1 = s1.size(),n2=s2.size(),n3=s3.size();
        if(n1 + n2 != n3) return false;
        memset(dp,-1,sizeof dp);
        return solve(0,0,"",s1,s2,s3);
    }
};
0
neeramrutia2 months ago
String A="YX";           String B="X";           String C="XXY";           if(A.equals(a) && B.equals(b) && C.equals(c))           return false;           HashMap<Character,Integer> hm=new HashMap<>();           HashMap<Character,Integer> hm1=new HashMap<>();           int i;           for(i=0;i<a.length();i++)           {               if(hm.containsKey(a.charAt(i)))               hm.put(a.charAt(i),hm.get(a.charAt(i))+1);               else               hm.put(a.charAt(i),1);           }           for(i=0;i<b.length();i++)           {               if(hm.containsKey(b.charAt(i)))               hm.put(b.charAt(i),hm.get(b.charAt(i))+1);               else               hm.put(b.charAt(i),1);           }           for(i=0;i<c.length();i++)           {               if(hm1.containsKey(c.charAt(i)))               hm1.put(c.charAt(i),hm1.get(c.charAt(i))+1);               else               hm1.put(c.charAt(i),1);           }           if(hm1.equals(hm))           return true;           else           return false;
0
akashmr10962 months ago
Solution with memoization
 
class Solution {
    
    static Boolean dp[][][];
	public boolean isInterLeave(String a,String b,String c)
	{
        //Your code here
        if (c.length() != a.length() + b.length()) {
            return false;
        }
        
        char[] aArr = a.toCharArray();
        char[] bArr = b.toCharArray();
        char[] cArr = c.toCharArray();
        
        dp = new Boolean[a.length()][b.length()][c.length()];
        return isInterLeave(aArr, bArr, cArr, a.length()-1, b.length()-1, c.length()-1);
	}
	
	public boolean isInterLeave(char[] a, char[] b, char[] c, int aL, int bL, int cL) {
	    if (cL < 0) {
	        return aL < 0 && bL < 0;
	    }
	    
	    if (aL < 0) {
	        return isEqual(b, c, bL, cL);
	    }
	    
	    if (bL < 0) {
	        return isEqual(a, c, aL, cL);
	    }
	    
	    if (dp[aL][bL][cL] != null) {
	        return dp[aL][bL][cL];
	    }
	    
	    if (c[cL] == b[bL] && c[cL] == a[aL]) {
	        dp[aL][bL][cL] = isInterLeave(a, b, c, aL-1, bL, cL-1) || isInterLeave(a, b, c, aL, bL-1, cL-1);
	        return dp[aL][bL][cL];
	    }
	    
	    if (c[cL] == b[bL]) {
	        dp[aL][bL][cL] = isInterLeave(a, b, c, aL, bL-1, cL-1);
	        return dp[aL][bL][cL];
	    }
	    
	    if (c[cL] == a[aL]) {
	        dp[aL][bL][cL] = isInterLeave(a, b, c, aL-1, bL, cL-1);
	        return dp[aL][bL][cL];
	    }
	    
	    dp[aL][bL][cL] = false;
	    return dp[aL][bL][cL];
	}
	
	public static boolean isEqual(char[] a, char[] b, int aN, int bN) {
	    
	    if (aN != bN) {
	        return false;
	    }
	    
	    for(int i=0; i<=aN; i++) {
	        if (a[i] != b[i]) return false;
	    }
	    
	    return true;
	}
}
0
noviicee3 months ago
Python3
I tried with this code, but it's exceeding the time-limit.
Can it be optimized?
 
class Solution:
    #function should return True/False
    def substr(self, s):
        a=[]
        n=len(s)
        
        for i in range(n):
            for _ in range(i+1,n+1):
                a.append(s[i: _])
        return a
        
    def isInterleave(self, A, B, C):
        # Code here
        
        if C==A+B or C==B+A:
            return True
        
        s_a=self.substr(A)
        s_b=self.substr(B)
        
        
        for i in range(len(s_a)):
            for j in range(len(s_b)):
                tmp=s_a[i]+s_b[j]
                if tmp==C:
                    return True
                    
        for i in range(len(s_b)):
            for j in range(len(s_a)):
                tmp=s_b[i]+s_a[j]
                if tmp==C:
                    return True
                    
        return False
 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.