The Wayback Machine - https://web.archive.org/web/20250102143333/https://www.geeksforgeeks.org/find-if-a-string-is-interleaved-of-two-other-strings-dp-33/
Open In App

Check if a String is Interleaving of Other Two

Last Updated : 16 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given three strings s1, s2 and s3. Write a function that checks whether s3 is an interleaving of s1 and s2. s3 is said to be interleaving s1 and s2, if it contains all and only characters of s1 and s2 and order of all characters in individual strings is preserved. 

Input: s1 = “AB”, s2 = “C”, s3 = “ACB”,
Output: true
s3 has all characters of s1 and s2 and retains order of characters of s1.

Input: s1 = “XXY”, s2 = “XXZ”, s3 = “XXXXZY”,
Output: true
The string XXXXZY has all characters of the other two strings and in the same order.

Input: s1 = “YX”, s2 = “X”, s3 = “XXY”
Output: false
XXY is not interleaved of YX and X. The strings that can be formed are YXX and XYX

Simple Recursive (Exponential Time)

A simple solution is discussed here: Check whether a given string is an interleaving of two other given string. 
The simple solution will also work if the strings s1 and s2 have some common characters. For example, let the given string be s1 and the other strings be s2 and s3. Let s1 = “XXY”, string s2 = “XXZ” and string s3 = “XXZXXXY”.

To handle all cases, two possibilities need to be considered.

  • If the first character of s3 matches the first character of s1, we move one character ahead in s1 and s3 and recursively check.
  • If the first character of s3 matches the first character of s2, we move one character ahead in s2 and s3 and recursively check.
  • If none of the two characters match, return false.
  • If any of the above function returns true or s1, s2 and s3 are empty then return true else return false.
C++
// Cpp program to check if Check if a String is 
// Interleaving of Other Two using recursion 
#include<iostream>
using namespace std;

// i amnd j are indexes in s1 and s2 respectively
bool isILRec(string &s1, string &s2, string &s3, 
                                    int i, int j) {
    
    int k = i + j;
  
    // If all strings are fully traversed
    if (i == s1.size() && j == s2.size() && k == s3.size()) 
        return true;    

    // If any of the above mentioned two
    // possibilities then return true
    // otherwise return false.
    bool a = (i < s1.size()) && (s3[k] == s1[i]) && 
             isILRec(s1, s2, s3, i + 1, j);
    bool b = (j < s2.size()) && (s3[k] == s2[j]) && 
              isILRec(s1, s2, s3, i, j + 1);
    
    return a || b;
}

bool isIL(string& s1, string& s2, string& s3) {
  
    // A basic condition that must be ensured
    if (s1.size() + s2.size() != s3.size()) 
        return false;    
  
    return isILRec(s1, s2, s3, 0, 0);
}

int main() {
    string s1 = "XXY";
    string s2 = "XXZ";
    string s3 = "XXZXXXY";
    cout << (isIL(s1, s2, s3) ? "true" : "false") << endl;
    return 0;
}
C
// C program to check if Check if a String is 
// Interleaving of Other Two using recursion 
#include <stdio.h>
#include <string.h>
#include <stdbool.h>

// i and j are indexes in s1 and s2 respectively
bool isILRec(char *s1, char *s2, char *s3, int i, int j) {
    
    int k = i + j;
  
    // If all strings are fully traversed
    if (i == strlen(s1) && j == strlen(s2) && k == strlen(s3)) 
        return true;    

    // If any of the above mentioned two
    // possibilities then return true
    // otherwise return false.
    bool a = (i < strlen(s1)) && (s3[k] == s1[i]) && 
             isILRec(s1, s2, s3, i + 1, j);
    bool b = (j < strlen(s2)) && (s3[k] == s2[j]) && 
              isILRec(s1, s2, s3, i, j + 1);
    
    return a || b;
}

bool isIL(char *s1, char *s2, char *s3) {
  
    // A basic condition that must be ensured
    if (strlen(s1) + strlen(s2) != strlen(s3)) 
        return false;    
    
    return isILRec(s1, s2, s3, 0, 0);
}

int main() {
    char s1[] = "XXY";
    char s2[] = "XXZ";
    char s3[] = "XXZXXXY";
    printf("%s\n", isIL(s1, s2, s3) ? "true" : "false");

    return 0;
}
Java
// Java program to check if Check if a String is 
// Interleaving of Other Two using recursion 
class GfG {
  
    // i and j are indexes in s1 and s2 respectively
    static boolean isILRec(String s1, String s2, String s3, int i, int j) {
        int k = i + j;
      
        // If all strings are fully traversed
        if (i == s1.length() && j == s2.length() && k == s3.length()) 
            return true;    
    
        // If any of the above mentioned two
        // possibilities then return true
        // otherwise return false.
        boolean a = (i < s1.length()) && (s3.charAt(k) == s1.charAt(i)) && 
                   isILRec(s1, s2, s3, i + 1, j);
        boolean b = (j < s2.length()) && (s3.charAt(k) == s2.charAt(j)) && 
                   isILRec(s1, s2, s3, i, j + 1);
        
        return a || b;
    }
    
    static boolean isIL(String s1, String s2, String s3) {
      
        // A basic condition that must be ensured
        if (s1.length() + s2.length() != s3.length()) 
            return false;    
    
        return isILRec(s1, s2, s3, 0, 0);
    }
    
    public static void main(String[] args) {
        String s1 = "XXY";
        String s2 = "XXZ";
        String s3 = "XXZXXXY";
        System.out.println(isIL(s1, s2, s3) ? "true" : "false");
    }
}
Python
# Python program to check if Check if a String is 
# Interleaving of Other Two using recursion 

def isILRec(s1, s2, s3, i, j):

    # i and j are indexes in s1 and s2 respectively
    k = i + j
    
    # If all strings are fully traversed
    if i == len(s1) and j == len(s2) and k == len(s3):
        return True

    # If any of the above mentioned two
    # possibilities then return true
    # otherwise return false.
    a = (i < len(s1)) and (s3[k] == s1[i]) and isILRec(s1, s2, s3, i + 1, j)
    b = (j < len(s2)) and (s3[k] == s2[j]) and isILRec(s1, s2, s3, i, j + 1)
    
    return a or b

def isIL(s1, s2, s3):
  
    # A basic condition that must be ensured
    if len(s1) + len(s2) != len(s3):
        return False
    
    return isILRec(s1, s2, s3, 0, 0)

if __name__ == "__main__":
    s1 = "XXY"
    s2 = "XXZ"
    s3 = "XXZXXXY"
    print("true" if isIL(s1, s2, s3) else "false")
C#
// C# program to check if Check if a String is 
// Interleaving of Other Two using recursion 
using System;

class GfG
{
    // i and j are indexes in s1 and s2 respectively
    static bool isILRec(string s1, string s2, string s3, int i, int j)
    {
        int k = i + j;
      
        // If all strings are fully traversed
        if (i == s1.Length && j == s2.Length && k == s3.Length) 
            return true;    
    
        // If any of the above mentioned two
        // possibilities then return true
        // otherwise return false.
        bool a = (i < s1.Length) && (s3[k] == s1[i]) && 
                 isILRec(s1, s2, s3, i + 1, j);
        bool b = (j < s2.Length) && (s3[k] == s2[j]) && 
                 isILRec(s1, s2, s3, i, j + 1);
        
        return a || b;
    }
    
    static bool isIL(string s1, string s2, string s3)
    {
        // A basic condition that must be ensured
        if (s1.Length + s2.Length != s3.Length) 
            return false;    
    
        return isILRec(s1, s2, s3, 0, 0);
    }
    
    static void Main(string[] args)
    {
        string s1 = "XXY";
        string s2 = "XXZ";
        string s3 = "XXZXXXY";
        Console.WriteLine(isIL(s1, s2, s3) ? "true" : "false");
    }
}
JavaScript
// JavaScript program to check if Check if a String is 
// Interleaving of Other Two using recursion 
function isILRec(s1, s2, s3, i, j) {

    // i and j are indexes in s1 and s2 respectively
    let k = i + j;

    // If all strings are fully traversed
    if (i === s1.length && j === s2.length && k === s3.length)
        return true;

    // If any of the above mentioned two
    // possibilities then return true
    // otherwise return false.
    let a = (i < s1.length) && (s3[k] === s1[i]) && isILRec(s1, s2, s3, i + 1, j);
    let b = (j < s2.length) && (s3[k] === s2[j]) && isILRec(s1, s2, s3, i, j + 1);
    
    return a || b;
}

function isIL(s1, s2, s3) {

    // A basic condition that must be ensured
    if (s1.length + s2.length !== s3.length)
        return false;
    
    return isILRec(s1, s2, s3, 0, 0);
}

let s1 = "XXY";
let s2 = "XXZ";
let s3 = "XXZXXXY";
console.log(isIL(s1, s2, s3) ? "true" : "false");

Output
false
true
true
false
true


Time Complexity: Exponential O(2 ^ min(m, n))

Using Memoization:

The above recursive solution certainly has many overlapping sub-problems. For example, if we consider s1 = “XXX”, s2 = “XXX” and s3 = “XXXXXX” and draw a recursion tree, there will be many overlapping subproblems. Therefore, like any other typical Dynamic Programming problems, we can solve it by creating a table and store results of sub-problems. Below is a memoization based solution that creates a 2D memo array.

  • We mainly create a 2D memo array memo of size (m+1)x(n+1). Note that there are two parameters that change in the recursive solution and values of these parameters go from 0 to m and 0 to n respectively.
  • memo[i][j] is true (or 1) if prefix of length i+j is an interleaving of length i prefix of s1 and prefix of length j of s2.
  • We initialize the memo array as -1 and before making any recursive calls check if the value is already computed and once we compute a value, we store it in the memo array.
C++
// Cpp program to check if Check if a String is 
// Interleaving of Other Two using memoization 
#include <iostream>
#include <vector>
using namespace std;

bool isILRec(const string& s1, const string& s2, 
                  const string& s3, int i, int j, 
                     vector<vector<int>>& memo) {
    int k = i+j;
    int m = s1.size(), n = s2.size();
  
    // Base case: If all strings are fully traversed
    if (i == m && j == n && k == s3.size()) 
        return true;    

    // If we have already solved this subproblem, 
    // return the stored result
    if (memo[i][j] != -1) {
        return memo[i][j];
    }
  
    // Check if next characcter of s1 maatchs with
    // with the next one of s3
    bool a = (i < m && s1[i] == s3[k]) && 
            isILRec(s1, s2, s3, i + 1, j, memo);

    // Check if next characcter of s2 maatchs with
    // with the next one of s3  
    bool b = (j < n && s2[j] == s3[k]) && 
            isILRec(s1, s2, s3, i, j + 1, memo);

    return memo[i][j] = a || b;
}

bool isIL(const string& s1, const string& s2, const string& s3) {
  
    int m = s1.size(), n = s2.size();
  
    // A basic condition that must be ensured
    if (m + n != s3.size()) 
        return false;    
  
    // Intiialize memo with -1 and make Recursive function call
    vector<vector<int>> memo(m + 1, vector<int>(n + 1, -1));  
    return isILRec(s1, s2, s3, 0, 0, memo);
}

int main() {
    string s1 = "XXY";
    string s2 = "XXZ";
    string s3 = "XXZXXXY";
    cout << (isIL(s1, s2, s3) ? "true" : "false") << endl;
    return 0;
}
Java
// Java

import java.util.Arrays;

class GfG {
   
    // i and j are indexes in s1 and s2 respectively
    static boolean isILRec(String s1, String s2, String s3, int i, int j, int[][] memo) {
        int k = i + j;
        int m = s1.length();
        int n = s2.length();
      
        // Base case: If all strings are fully traversed
        if (i == m && j == n && k == s3.length())
            return true;    
    
        // If we have already solved this subproblem, 
        // return the stored result
        if (memo[i][j] != -1) {
            return memo[i][j] == 1;
        }
      
        // Check if next character of s1 matches with
        // with the next one of s3
        boolean a = false;
        if (i < m && s1.charAt(i) == s3.charAt(k)) {
            a = isILRec(s1, s2, s3, i + 1, j, memo);
        }
    
        // Check if next character of s2 matches with
        // with the next one of s3  
        boolean b = false;
        if (j < n && s2.charAt(j) == s3.charAt(k)) {
            b = isILRec(s1, s2, s3, i, j + 1, memo);
        }
        
        memo[i][j] = a || b ? 1 : 0;
        return a || b;
    }
    
    static boolean isIL(String s1, String s2, String s3) {
        int m = s1.length();
        int n = s2.length();
      
        // A basic condition that must be ensured
        if (m + n != s3.length())
            return false;    
      
        // Initialize memo with -1 and make Recursive function call
        int[][] memo = new int[m + 1][n + 1];
        for(int[] row: memo)
            Arrays.fill(row, -1);
        return isILRec(s1, s2, s3, 0, 0, memo);
    }
    
    public static void main(String[] args) {
        String s1 = "XXY";
        String s2 = "XXZ";
        String s3 = "XXZXXXY";
        System.out.println(isIL(s1, s2, s3) ? "true" : "false");
    }
}
Python
# Python

def isILRec(s1, s2, s3, i, j, memo):
    # i and j are indexes in s1 and s2 respectively
    k = i + j
    m = len(s1)
    n = len(s2)
  
    # Base case: If all strings are fully traversed
    if i == m and j == n and k == len(s3):
        return True    

    # If we have already solved this subproblem, 
    # return the stored result
    if memo[i][j] != -1:
        return memo[i][j] == 1
  
    # Check if next character of s1 matches with
    # with the next one of s3
    a = False
    if i < m and s1[i] == s3[k]:
        a = isILRec(s1, s2, s3, i + 1, j, memo)
    
    # Check if next character of s2 matches with
    # with the next one of s3  
    b = False
    if j < n and s2[j] == s3[k]:
        b = isILRec(s1, s2, s3, i, j + 1, memo)
    
    memo[i][j] = 1 if a or b else 0
    return a or b

def isIL(s1, s2, s3):
    # A basic condition that must be ensured
    m = len(s1)
    n = len(s2)
    if m + n != len(s3):
        return False    

    # Initialize memo with -1 and make Recursive function call
    memo = [[-1 for _ in range(n+1)] for _ in range(m+1)]
    return isILRec(s1, s2, s3, 0, 0, memo)

def main():
    s1 = "XXY"
    s2 = "XXZ"
    s3 = "XXZXXXY"
    print("true" if isIL(s1, s2, s3) else "false")

if __name__ == "__main__":
    main()
C#
// C#

using System;

class GfG {
    // i and j are indexes in s1 and s2 respectively
    static bool isILRec(string s1, string s2, string s3, int i, int j, int[,] memo) {
        int k = i + j;
        int m = s1.Length;
        int n = s2.Length;
      
        // Base case: If all strings are fully traversed
        if (i == m && j == n && k == s3.Length)
            return true;    
    
        // If we have already solved this subproblem, 
        // return the stored result
        if (memo[i,j] != -1)
            return memo[i,j] == 1;
      
        // Check if next character of s1 matches with
        // with the next one of s3
        bool a = false;
        if (i < m && s1[i] == s3[k])
            a = isILRec(s1, s2, s3, i + 1, j, memo);
    
        // Check if next character of s2 matches with
        // with the next one of s3  
        bool b = false;
        if (j < n && s2[j] == s3[k])
            b = isILRec(s1, s2, s3, i, j + 1, memo);
        
        memo[i,j] = (a || b) ? 1 : 0;
        return a || b;
    }
    
    static bool isIL(string s1, string s2, string s3) {
        int m = s1.Length;
        int n = s2.Length;
      
        // A basic condition that must be ensured
        if (m + n != s3.Length)
            return false;    
      
        // Initialize memo with -1 and make Recursive function call
        int[,] memo = new int[m + 1, n + 1];
        for(int i =0; i <= m; i++)
            for(int j=0; j<=n; j++)
                memo[i,j] = -1;
        return isILRec(s1, s2, s3, 0, 0, memo);
    }
    
    static void Main(string[] args) {
        string s1 = "XXY";
        string s2 = "XXZ";
        string s3 = "XXZXXXY";
        Console.WriteLine(isIL(s1, s2, s3) ? "true" : "false");
    }
}
JavaScript
// JavaScript

function isILRec(s1, s2, s3, i, j, memo) {

    // i and j are indexes in s1 and s2 respectively
    let k = i + j;
    let m = s1.length;
    let n = s2.length;
  
    // Base case: If all strings are fully traversed
    if (i === m && j === n && k === s3.length)
        return true;    

    // If we have already solved this subproblem, 
    // return the stored result
    if (memo[i][j] !== -1) {
        return memo[i][j] === 1;
    }
  
    // Check if next character of s1 matches with
    // with the next one of s3
    let a = false;
    if (i < m && s1[i] === s3[k]) {
        a = isILRec(s1, s2, s3, i + 1, j, memo);
    }

    // Check if next character of s2 matches with
    // with the next one of s3  
    let b = false;
    if (j < n && s2[j] === s3[k]) {
        b = isILRec(s1, s2, s3, i, j + 1, memo);
    }
    
    memo[i][j] = (a || b) ? 1 : 0;
    return a || b;
}

function isIL(s1, s2, s3) {
    // A basic condition that must be ensured
    let m = s1.length;
    let n = s2.length;
    if (m + n !== s3.length)
        return false;    

    // Initialize memo with -1 and make Recursive function call
    let memo = Array(m + 1).fill(null).map(() => Array(n + 1).fill(-1));
    return isILRec(s1, s2, s3, 0, 0, memo);
}

function main() {
    let s1 = "XXY";
    let s2 = "XXZ";
    let s3 = "XXZXXXY";
    console.log(isIL(s1, s2, s3) ? "true" : "false");
}

main();

Output
false
true
true
false
true

Time Complexity: O(m * n).
Auxiliary Space : O((m * n). 

Using Dynamic Programming:

  • We mainly create a 2D array dp of size (m+1)x(n+1). Note that there are two parameters that change in the recursive solution and values of these parameters go from 0 to m and 0 to n respectively.
  • dp[i][j] is true (or 1) if prefix of length i+j of s3 is an interleaving of length i prefix of s1 and prefix of length j of s2.
  • We fill dpin bottom up manner. We first fill the known values when i is 0 and when j is 0.
  • Then we fill the remaining values using recursive formula. 
  • We return dp[m][n] at the end
C++
// Cpp program to check if Check if a String is Interleaving
// of Other Two using Dynamic Programming
#include <iostream>
#include <vector>
#include <string>
using namespace std;

// The main function that
// returns true if s3 is
// an interleaving of s1
// and s2, otherwise false.
bool isIL(string& s1, string& s2, string& s3) {
  
    int m = s1.size(), n = s2.size();

    // s3 can be an interleaving of s1 and s2 only if
    // the sum of lengths of s1 & s2 is equal to the length of s3.
    if (m + n != s3.size()) return false;

    vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));

    // Handle the corner case where both s1 and s2 are empty
    dp[0][0] = true;

    // Fill the first row (when s1 is empty)
    for (int j = 1; j <= n; ++j) {
        dp[0][j] = (s2[j - 1] == s3[j - 1]) && dp[0][j - 1];
    }

    // Fill the first column (when s2 is empty)
    for (int i = 1; i <= m; ++i) {
        dp[i][0] = (s1[i - 1] == s3[i - 1]) && dp[i - 1][0];
    }

    // Process all characters of s1 and s2
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            int k = i+j;
            dp[i][j] = (s1[i - 1] == s3[k - 1] && dp[i - 1][j]) ||
                       (s2[j - 1] == s3[k - 1] && dp[i][j - 1]);
        }
    }

    return dp[m][n];
}

int main() {
      string s1 = "XXY";
    string s2 = "XXZ";
    string s3 = "XXZXXXY";
    cout << (isIL(s1, s2, s3) ? "true" : "false") << endl;
    return 0;
}
Java
// Java program to check if a String is Interleaving 
// of Other Two using Dynamic Programming

import java.util.Arrays;

class GfG {
  
    // The main function that
    // returns true if s3 is
    // an interleaving of s1
    // and s2, otherwise false.
    static boolean isIL(String s1, String s2, String s3) {
        int m = s1.length();
        int n = s2.length();

        // s3 can be an interleaving of s1 and s2 only if
        // the sum of lengths of s1 & s2 is equal to the length of s3.
        if (m + n != s3.length()) return false;

        boolean[][] dp = new boolean[m + 1][n + 1];

        // Handle the corner case where both s1 and s2 are empty
        dp[0][0] = true;

        // Fill the first row (when s1 is empty)
        for (int j = 1; j <= n; ++j) {
            dp[0][j] = (s2.charAt(j - 1) == s3.charAt(j - 1)) && dp[0][j - 1];
        }

        // Fill the first column (when s2 is empty)
        for (int i = 1; i <= m; ++i) {
            dp[i][0] = (s1.charAt(i - 1) == s3.charAt(i - 1)) && dp[i - 1][0];
        }

        // Process all characters of s1 and s2
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                int k = i + j;
                dp[i][j] = (s1.charAt(i - 1) == s3.charAt(k - 1) && dp[i - 1][j]) ||
                           (s2.charAt(j - 1) == s3.charAt(k - 1) && dp[i][j - 1]);
            }
        }

        return dp[m][n];
    }

    public static void main(String[] args) {
        String s1 = "XXY";
        String s2 = "XXZ";
        String s3 = "XXZXXXY";
        System.out.println(isIL(s1, s2, s3) ? "true" : "false");
    }
}
Python
# Python program to check if a String is Interleaving 
# of Other Two using Dynamic Programming

def isIL(s1, s2, s3):
    # The main function that
    # returns true if s3 is
    # an interleaving of s1
    # and s2, otherwise false.
    m = len(s1)
    n = len(s2)

    # s3 can be an interleaving of s1 and s2 only if
    # the sum of lengths of s1 & s2 is equal to the length of s3.
    if m + n != len(s3):
        return False

    dp = [[False]*(n+1) for _ in range(m+1)]

    # Handle the corner case where both s1 and s2 are empty
    dp[0][0] = True

    # Fill the first row (when s1 is empty)
    for j in range(1, n+1):
        dp[0][j] = (s2[j-1] == s3[j-1]) and dp[0][j-1]

    # Fill the first column (when s2 is empty)
    for i in range(1, m+1):
        dp[i][0] = (s1[i-1] == s3[i-1]) and dp[i-1][0]

    # Process all characters of s1 and s2
    for i in range(1, m+1):
        for j in range(1, n+1):
            k = i + j
            dp[i][j] = (s1[i-1] == s3[k-1] and dp[i-1][j]) or \
                       (s2[j-1] == s3[k-1] and dp[i][j-1])

    return dp[m][n]

def main():
    s1 = "XXY"
    s2 = "XXZ"
    s3 = "XXZXXXY"
    print("true" if isIL(s1, s2, s3) else "false")

if __name__ == "__main__":
    main()
C#
// C# program to check if a String is Interleaving
// of Other Two using Dynamic Programming

using System;

class GfG { 
  
    // The main function that
    // returns true if s3 is
    // an interleaving of s1
    // and s2, otherwise false.
    static bool isIL(string s1, string s2, string s3) {
        int m = s1.Length;
        int n = s2.Length;

        // s3 can be an interleaving of s1 and s2 only if
        // the sum of lengths of s1 & s2 is equal to the length of s3.
        if (m + n != s3.Length) return false;

        bool[,] dp = new bool[m + 1, n + 1];

        // Handle the corner case where both s1 and s2 are empty
        dp[0, 0] = true;

        // Fill the first row (when s1 is empty)
        for (int j = 1; j <= n; ++j) {
            dp[0, j] = (s2[j - 1] == s3[j - 1]) && dp[0, j - 1];
        }

        // Fill the first column (when s2 is empty)
        for (int i = 1; i <= m; ++i) {
            dp[i, 0] = (s1[i - 1] == s3[i - 1]) && dp[i - 1, 0];
        }

        // Process all characters of s1 and s2
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                int k = i + j;
                dp[i, j] = (s1[i - 1] == s3[k - 1] && dp[i - 1, j]) ||
                           (s2[j - 1] == s3[k - 1] && dp[i, j - 1]);
            }
        }

        return dp[m, n];
    }

    static void Main(string[] args) {
        string s1 = "XXY";
        string s2 = "XXZ";
        string s3 = "XXZXXXY";
        Console.WriteLine(isIL(s1, s2, s3) ? "true" : "false");
    }
}
JavaScript
// JavaScript program to check if a String is Interleaving 
// of Other Two using Dynamic Programming

function isIL(s1, s2, s3) {

    // The main function that
    // returns true if s3 is
    // an interleaving of s1
    // and s2, otherwise false.
    let m = s1.length;
    let n = s2.length;

    // s3 can be an interleaving of s1 and s2 only if
    // the sum of lengths of s1 & s2 is equal to the length of s3.
    if (m + n !== s3.length) return false;

    let dp = Array(m + 1).fill(null).map(() => Array(n + 1).fill(false));

    // Handle the corner case where both s1 and s2 are empty
    dp[0][0] = true;

    // Fill the first row (when s1 is empty)
    for (let j = 1; j <= n; ++j) {
        dp[0][j] = (s2[j - 1] === s3[j - 1]) && dp[0][j - 1];
    }

    // Fill the first column (when s2 is empty)
    for (let i = 1; i <= m; ++i) {
        dp[i][0] = (s1[i - 1] === s3[i - 1]) && dp[i - 1][0];
    }

    // Process all characters of s1 and s2
    for (let i = 1; i <= m; ++i) {
        for (let j = 1; j <= n; ++j) {
            let k = i + j;
            dp[i][j] = (s1[i - 1] === s3[k - 1] && dp[i - 1][j]) ||
                       (s2[j - 1] === s3[k - 1] && dp[i][j - 1]);
        }
    }

    return dp[m][n];
}

function main() {
    let s1 = "XXY";
    let s2 = "XXZ";
    let s3 = "XXZXXXY";
    console.log(isIL(s1, s2, s3) ? "true" : "false");
}

main();

Output
false
true
true
false
true

Time Complexity: O(m * n).
Auxiliary Space : O((m * n). 

Illustration of the DP Approach:
If s3 is the interleaved string of s1 and s2 then there exists a path from the top left of the dp to the bottom right. That is if we can go from index 0,0 to n,m while matching characters of all s1 and s2 with s3 then s3 is interleaved of s1 and s2.

Let s1 be “XXY”, s2 be “XXZ” and s3 be “XXZXXY” then the path would look something like this:

 XXY 
X1000
X1000
Z1000
 111R

let us consider one more example, let s1 be “ABC”, s2 be “DEF” and s3 be “ADBECF”, then the path would look something like this:

 DEF 
A1000
B1100
C0110
 001R

If there exists a path through which we can reach R, then s3 is the interleaved strings of s1 and s2.

1. We will first create a matrix dp to store the path since one path can be explored multiple times, the Matrix index dp[i][j] will store if there exists a path from this index or not.

2. If we are at i’th index of s1 and j’th index of s2 and s3[i+j] matches both s1[i] and s2[j] then we explore both the paths that are we will go right and down i.e. we will explore index i+1,j and j+1,i.

3. If s3[i+j] only matches with s1[i] or s2[j] then we will go just down or right respectively that is i+1,j or i,j+1.



Similar Reads

three90RightbarBannerImg