Check if a String is Interleaving of Other Two
Last Updated :
16 Nov, 2024
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");
Outputfalse
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();
Outputfalse
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();
Outputfalse
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:
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:
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
Check if a String is Interleaving of Other Two
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 = "A
15+ min read
Print all interleavings of given two strings
Given two strings str1 and str2, write a function that prints all interleavings of the given two strings. You may assume that all characters in both strings are different Example: Input: str1 = "AB", str2 = "CD"Output: ABCD ACBD ACDB CABD CADB CDABInput: str1 = "AB", str2 = "C"Output: ABC ACB CAB An
14 min read
Check if two strings are same or not
Given two strings, the task is to check if these two strings are identical(same) or not. Examples: Input: s1 = "abc", s2 = "abc" Output: Yes Input: s1 = "", s2 = "" Output: Yes Input: s1 = "GeeksforGeeks", s2 = "Geeks" Output: No Using (==) in C++/Python/C#, equals in Java and === in JavaScript[GFGT
3 min read
Check if a string is Isogram or not
Given a word or phrase, check if it is an isogram or not. An Isogram is a word in which no letter occurs more than once Examples: Input: MachineOutput: TrueExplanation: "Machine" does not have any character repeating, it is an Isogram Input : GeekOutput : FalseExplanation: "Geek" has 'e' as repeatin
9 min read
Check if two strings are permutation of each other
Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that
14 min read
Check if concatenation of two strings is balanced or not
Given two bracket sequences S1 and S2 consisting of '(' and ')'. The task is to check if the string obtained by concatenating both the sequences is balanced or not. Concatenation can be done by s1+s2 or s2+s1. Examples: Input: s1 = ")()(())))", s2 = "(()(()(" Output: Balanced s2 + s1 = "(()(()()()((
15 min read
Interleaving of two given strings with no common characters
Given three strings s1, s2 and s3. check whether s3 is an interleaving of s1 and s2. It may be assumed that there is no common character between s1 and s2 A string s3 is said to be interleaving s1 and s2, if it contains all characters of s1 and s2 and order of all characters in individual strings is
10 min read
Check whether a given string is Heterogram or not
Given a string S. The task is to check whether a the given string is Heterogram or not. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Examples: Input : S = "the big dwarf only jumps" Output : Yes Each alphabet in the string S is occurred only o
4 min read
Check if one string is subsequence of other
Given two strings s1 and s2, find if the first string is a Subsequence of the second string, i.e. if s1 is a subsequence of s2. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. Examples : Input: s1 =
10 min read
Check if Strings Are Rotations of Each Other
Given two string s1 and s2 of same length, the task is to check whether s2 is a rotation of s1. Examples: Input: s1 = "abcd", s2 = "cdab"Output: trueExplanation: After 2 right rotations, s1 will become equal to s2. Input: s1 = "aab", s2 = "aba"Output: trueExplanation: After 1 left rotation, s1 will
15+ min read
Check if two strings have a common substring
You are given two strings str1 and str2. You have to check if the two strings share a common substring. Examples : Input : str1 = "HELLO" str2 = "WORLD" Output : YES Explanation : The substrings "O" and "L" are common to both str1 and str2 Input : str1 = "HI" str2 = "ALL" Output : NO Explanation : B
5 min read
Queries to check if string B exists as substring in string A
Given two strings A, B and some queries consisting of an integer i, the task is to check whether the sub-string of A starting from index i and ending at index i + length(B) - 1 equals B or not. If equal then print Yes else print No. Note that i + length(B) will always be smaller than length(A). Exam
15+ min read
Check if a string is concatenation of another given string
Given two strings str1 and str2 of length N and M respectively, the task is to check if the string str1 can be formed by concatenating the string str2 repetitively or not. Examples: Input: str1 = “abcabcabc”, str2 = “abc”Output: YesExplanation: Concatenating the string str2 thrice generates the stri
7 min read
Check if one string can be converted to other using given operation
Given two strings S and T of same length. The task is to determine whether or not we can build a string A(initially empty) equal to string T by performing the below operations. Delete the first character of S and add it at the front of A. Delete the first character of S and add it at the back of A.
15+ min read
Check if the given string is valid English word or not
Given string str, the task is to check if this string str consists of valid English words or not. A string is known as a valid English word if it meets all the below criteria- The string can have an uppercase character as the first character only.The string can only have lowercase characters.The str
15 min read
Check if a string is substring of another
Given two strings txt and pat, the task is to find if pat is a substring of txt. If yes, return the index of the first occurrence, else return -1. Examples : Input: txt = "geeksforgeeks", pat = "eks"Output: 2Explanation: String "eks" is present at index 2 and 9, so 2 is the smallest index. Input: tx
8 min read
Check if a string is Colindrome
Given a string, check if it is Colindrome or not. A string is said to be colindrome if it has consecutive 3 alphabets followed by the reverse of these 3 alphabets and so on. Examples : Input : cappaccappac Output : String is colindrome Input : mollomaappaa Output : String is Colindrome Approach : Ta
6 min read
Checking valid shuffle of two Strings
Given two strings str1 and str2, and a third-string shuffle, determine if shuffle is a valid shuffle of str1 and str2, where a valid shuffle contains all characters from str1 and str2 occurring the same number of times, regardless of order. Print "YES" if valid, and "NO" otherwise. Examples: Input:
7 min read
Check if given words are present in a string
Given a big string and an array of small strings, all of which are smaller in length than the big string. The task is to create an array of booleans, where each boolean represents whether the small string at that index in the array of small strings is contained in the big string. Note : that you can
15+ min read
Find one extra character in a string
Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is to find the extra character in the second string. Examples: Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B con
15+ min read