Print all interleavings of given two strings
Last Updated :
16 Aug, 2024
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
CDAB
Input: str1 = "AB", str2 = "C"
Output:
ABC
ACB
CAB
An interleaved string of given two strings preserves the order of characters in individual strings. For example, in all the interleavings of above first example, 'A' comes before 'B' and 'C' comes before 'D'.
Let the length of str1 be m and the length of str2 be n. Let us assume that all characters in str1 and str2 are different. Let count(m, n) be the count of all interleaved strings in such strings. The value of count(m, n) can be written as following.
count(m, n) = count(m-1, n) + count(m, n-1)
count(1, 0) = 1 and count(0, 1) = 1
To print all interleavings, we can first fix the first character of str1[0..m-1] in output string, and recursively call for str1[1..m-1] and str2[0..n-1]. And then we can fix the first character of str2[0..n-1] and recursively call for str1[0..m-1] and str2[1..n-1]. Thanks to akash01 for providing following C implementation.
C++
// C++ program to print all interleavings of given two strings
#include <bits/stdc++.h>
using namespace std;
// The main function that recursively prints all interleavings.
// The variable iStr is used to store all interleavings (or
// output strings) one by one.
// i is used to pass next available place in iStr
void printIlsRecur (char *str1, char *str2, char *iStr, int m,
int n, int i)
{
// Base case: If all characters of str1 and str2 have been
// included in output string, then print the output string
if (m == 0 && n == 0)
cout << iStr << endl ;
// If some characters of str1 are left to be included, then
// include the first character from the remaining characters
// and recur for rest
if (m != 0)
{
iStr[i] = str1[0];
printIlsRecur (str1 + 1, str2, iStr, m - 1, n, i + 1);
}
// If some characters of str2 are left to be included, then
// include the first character from the remaining characters
// and recur for rest
if (n != 0)
{
iStr[i] = str2[0];
printIlsRecur(str1, str2 + 1, iStr, m, n - 1, i + 1);
}
}
// Allocates memory for output string and uses printIlsRecur()
// for printing all interleavings
void printIls (char *str1, char *str2, int m, int n)
{
// allocate memory for the output string
char *iStr= new char[((m + n + 1)*sizeof(char))];
// Set the terminator for the output string
iStr[m + n] = '\0';
// print all interleavings using printIlsRecur()
printIlsRecur (str1, str2, iStr, m, n, 0);
// free memory to avoid memory leak
free(iStr);
}
// Driver code
int main()
{
char str1[] = "AB";
char str2[] = "CD";
printIls (str1, str2, strlen(str1), strlen(str2));
return 0;
}
// This is code is contributed by rathbhupendra
C
// C program to print all interleavings of given two strings
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// The main function that recursively prints all interleavings.
// The variable iStr is used to store all interleavings (or
// output strings) one by one.
// i is used to pass next available place in iStr
void printIlsRecur (char *str1, char *str2, char *iStr, int m,
int n, int i)
{
// Base case: If all characters of str1 and str2 have been
// included in output string, then print the output string
if (m==0 && n==0)
printf("%s\n", iStr) ;
// If some characters of str1 are left to be included, then
// include the first character from the remaining characters
// and recur for rest
if (m != 0)
{
iStr[i] = str1[0];
printIlsRecur (str1 + 1, str2, iStr, m-1, n, i+1);
}
// If some characters of str2 are left to be included, then
// include the first character from the remaining characters
// and recur for rest
if (n != 0)
{
iStr[i] = str2[0];
printIlsRecur(str1, str2+1, iStr, m, n-1, i+1);
}
}
// Allocates memory for output string and uses printIlsRecur()
// for printing all interleavings
void printIls (char *str1, char *str2, int m, int n)
{
// allocate memory for the output string
char *iStr= (char*)malloc((m+n+1)*sizeof(char));
// Set the terminator for the output string
iStr[m+n] = '\0';
// print all interleavings using printIlsRecur()
printIlsRecur (str1, str2, iStr, m, n, 0);
// free memory to avoid memory leak
free(iStr);
}
// Driver program to test above functions
int main()
{
char str1[] = "AB";
char str2[] = "CD";
printIls (str1, str2, strlen(str1), strlen(str2));
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
/*
* This methods prints interleaving string of two
* strings
* @param s1 String 1
* @param i current index of s1
* @param s2 String 2
* @param j Current index of s2
* @param asf String containing interleaving string of
* s1 and s2
*
*/
static void printInterLeaving(String s1, int i,
String s2, int j,
String asf)
{
if (i == s1.length() && j == s2.length()) {
System.out.println(asf);
}
// Either we will start with string 1
if (i < s1.length())
printInterLeaving(s1, i + 1, s2, j,
asf + s1.charAt(i));
// Or with string 2
if (j < s2.length())
printInterLeaving(s1, i, s2, j + 1,
asf + s2.charAt(j));
}
/*
* Main function executed by JVM
* @param args String array
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
String s1 = "AB"; // String 1
String s2 = "CD"; // String 2
printInterLeaving(s1, 0, s2, 0, "");
}
}
/* Code by mahi_07 */
Python
# Python program to print all interleavings of given two strings
# Utility function
def toString(List):
return "".join(List)
# The main function that recursively prints all interleavings.
# The variable iStr is used to store all interleavings (or output
# strings) one by one.
# i is used to pass next available place in iStr
def printIlsRecur(str1, str2, iStr, m, n, i):
# Base case: If all characters of str1 and str2 have been
# included in output string, then print the output string
if m==0 and n==0:
print (toString(iStr))
# If some characters of str1 are left to be included, then
# include the first character from the remaining characters
# and recur for rest
if m != 0:
iStr[i] = str1[0]
printIlsRecur(str1[1:], str2, iStr, m-1, n, i+1)
# If some characters of str2 are left to be included, then
# include the first character from the remaining characters
# and recur for rest
if n != 0:
iStr[i] = str2[0]
printIlsRecur(str1, str2[1:], iStr, m, n-1, i+1)
# Allocates memory for output string and uses printIlsRecur()
# for printing all interleavings
def printIls(str1, str2, m, n):
iStr = [''] * (m+n)
# print all interleavings using printIlsRecur()
printIlsRecur(str1, str2, iStr, m, n, 0)
# Driver program to test the above function
str1 = "AB"
str2 = "CD"
printIls(str1, str2, len(str1), len(str2))
# This code is contributed by Bhavya Jain
C#
using System;
public class GFG
{
// * This methods prints interleaving string of two
// * strings
// * @param s1 String 1
// * @param i current index of s1
// * @param s2 String 2
// * @param j Current index of s2
// * @param asf String containing interleaving string of
// * s1 and s2
// *
public static void printInterLeaving(String s1, int i, String s2, int j, String asf)
{
if (i == s1.Length && j == s2.Length)
{
Console.WriteLine(asf);
}
// Either we will start with string 1
if (i < s1.Length)
{
GFG.printInterLeaving(s1, i + 1, s2, j, asf + s1[i].ToString());
}
// Or with string 2
if (j < s2.Length)
{
GFG.printInterLeaving(s1, i, s2, j + 1, asf + s2[j].ToString());
}
}
// * Main function executed by JVM
// * @param args String array
public static void Main(String[] args)
{
// TODO Auto-generated method stub
var s1 = "AB";
// String 1
var s2 = "CD";
// String 2
GFG.printInterLeaving(s1, 0, s2, 0, "");
}
}
// This code is contributed by aadityaburujwale.
JavaScript
// Recursive function to print all interleavings of the two strings
function printIlsRecur(str1, str2, iStr, m, n, i)
{
// Base case: If all characters of str1 and str2
// have been included in output string, then print the output string
if (m === 0 && n === 0) {
console.log(iStr.join(""));
}
// If some characters of str1 are left to be included, then include the first character from the remaining characters and recur for rest
if (m !== 0) {
iStr[i] = str1[0];
printIlsRecur(str1.slice(1), str2, iStr, m - 1, n, i + 1);
}
// If some characters of str2 are left to be included, then include the first character from the remaining characters and recur for rest
if (n !== 0) {
iStr[i] = str2[0];
printIlsRecur(str1, str2.slice(1), iStr, m, n - 1, i + 1);
}
}
// Function to print all interleavings of the two strings
function printIls(str1, str2, m, n) {
// Allocate memory for the output string
let iStr = new Array(m + n);
// Print all interleavings using printIlsRecur
printIlsRecur(str1, str2, iStr, m, n, 0);
}
// Example usage
let str1 = "AB";
let str2 = "CD";
printIls(str1, str2, str1.length, str2.length);
// This code is contributed by lokeshpotta20.
OutputABCD
ACBD
ACDB
CABD
CADB
CDAB
Time Complexity: O(2 ^ (m+n))
Auxiliary Space: O(1)
Approach 2: Using Buttom-Up Approach /Tabulation Method of Dynamic Programming
C++
#include <bits/stdc++.h>
using namespace std;
// Function to print interleavings of two strings
void printInterleavings(string str1, string str2)
{
int m = str1.length();
int n = str2.length();
// Create a 2D vector to store interleavings
vector<vector<vector<string> > > dp(
m + 1, vector<vector<string> >(n + 1));
// Base cases: If one of the strings is empty,
// return the other string
for (int i = 0; i <= m; i++) {
dp[i][0] = { str1.substr(0, i) };
}
for (int j = 0; j <= n; j++) {
dp[0][j] = { str2.substr(0, j) };
}
// Fill in the dynamic programming table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// Append the current character of str1 to
// each interleaved string from previous cells
dp[i][j] = dp[i - 1][j];
for (string& s : dp[i][j]) {
s += str1[i - 1];
}
// Append the current character of str2 to each
// interleaved string from previous cells
for (string& s : dp[i][j - 1]) {
dp[i][j].push_back(s + str2[j - 1]);
}
}
}
// Print all interleavings
for (const string& interleaved : dp[m][n]) {
cout << interleaved << endl;
}
}
// Example usage
int main()
{
string str1 = "AB";
string str2 = "CD";
printInterleavings(str1, str2);
return 0;
}
// THIS CODE IS CONTRIBUTED BY YASH
// AGARWAL(YASHAGARWAL2852002)
Java
import java.util.ArrayList;
public class GFG {
// Function to print interleavings of two strings
static void printInterleavings(String str1, String str2) {
int m = str1.length();
int n = str2.length();
// Create a 2D ArrayList to store interleavings
ArrayList<ArrayList<ArrayList<String>>> dp = new ArrayList<>();
for (int i = 0; i <= m; i++) {
ArrayList<ArrayList<String>> row = new ArrayList<>();
dp.add(row);
for (int j = 0; j <= n; j++) {
row.add(new ArrayList<>());
}
}
// Base cases: If one of the strings is empty,
// return the other string
for (int i = 0; i <= m; i++) {
dp.get(i).get(0).add(str1.substring(0, i));
}
for (int j = 0; j <= n; j++) {
dp.get(0).get(j).add(str2.substring(0, j));
}
// Fill in the dynamic programming table
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
// Append the current character of str1 to
// each interleaved string from previous cells
for (String s : dp.get(i - 1).get(j)) {
dp.get(i).get(j).add(s + str1.charAt(i - 1));
}
// Append the current character of str2 to each
// interleaved string from previous cells
for (String s : dp.get(i).get(j - 1)) {
dp.get(i).get(j).add(s + str2.charAt(j - 1));
}
}
}
// Print all interleavings
for (String interleaved : dp.get(m).get(n)) {
System.out.println(interleaved);
}
}
// Example usage
public static void main(String[] args) {
String str1 = "AB";
String str2 = "CD";
printInterleavings(str1, str2);
}
}
Python
def printInterleavings(str1, str2):
m, n = len(str1), len(str2)
dp = [[[] for _ in range(n+1)] for _ in range(m+1)]
# Base cases: If one of the strings is empty, return the
# other string
for i in range(m+1):
dp[i][0] = [str1[:i]]
for j in range(n+1):
dp[0][j] = [str2[:j]]
# Fill in the dynamic programming table
for i in range(1, m+1):
for j in range(1, n+1):
# Append the current character of str1 to each
# interleaved string from previous cells
dp[i][j] += [s + str1[i-1] for s in dp[i-1][j]]
# Append the current character of str2 to each
# interleaved string from previous cells
dp[i][j] += [s + str2[j-1] for s in dp[i][j-1]]
# Print all interleavings
for interleaved in dp[m][n]:
print(interleaved)
# Example usage
str1 = "AB"
str2 = "CD"
printInterleavings(str1, str2)
C#
using System;
using System.Collections.Generic;
public class GFG
{
// Function to print interleavings of two strings
static void PrintInterleavings(string str1, string str2)
{
int m = str1.Length;
int n = str2.Length;
// Create a 2D vector to store interleavings
List<List<List<string>>> dp = new List<List<List<string>>>();
for (int i = 0; i <= m; i++)
{
List<List<string>> row = new List<List<string>>();
dp.Add(row);
for (int j = 0; j <= n; j++)
{
row.Add(new List<string>());
}
}
// Base cases: If one of the strings is empty,
// return the other string
for (int i = 0; i <= m; i++)
{
dp[i][0].Add(str1.Substring(0, i));
}
for (int j = 0; j <= n; j++)
{
dp[0][j].Add(str2.Substring(0, j));
}
// Fill in the dynamic programming table
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
// Append the current character of str1 to
// each interleaved string from previous cells
foreach (string s in dp[i - 1][j])
{
dp[i][j].Add(s + str1[i - 1]);
}
// Append the current character of str2 to each
// interleaved string from previous cells
foreach (string s in dp[i][j - 1])
{
dp[i][j].Add(s + str2[j - 1]);
}
}
}
// Print all interleavings
foreach (string interleaved in dp[m][n])
{
Console.WriteLine(interleaved);
}
}
// Example usage
public static void Main(string[] args)
{
string str1 = "AB";
string str2 = "CD";
PrintInterleavings(str1, str2);
}
}
JavaScript
function printInterleavings(str1, str2) {
const m = str1.length;
const n = str2.length;
const dp = new Array(m + 1).fill(null).map(() =>
new Array(n + 1));
// Base cases: If one of the strings is empty,
// return the other string
for (let i = 0; i <= m; i++) {
dp[i][0] = [str1.slice(0, i)];
}
for (let j = 0; j <= n; j++) {
dp[0][j] = [str2.slice(0, j)];
}
// Fill in the dynamic programming table
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
// Append the current character of str1 to
// each interleaved string from previous cells
dp[i][j] = dp[i - 1][j].map(s => s + str1[i - 1]);
// Append the current character of str2 to each
// interleaved string from previous cells
dp[i][j] = dp[i][j] || [];
dp[i][j].push(...dp[i][j - 1].map(s => s + str2[j - 1]));
}
}
// Print all interleavings
for (const interleaved of dp[m][n]) {
console.log(interleaved);
}
}
// Example usage
const str1 = "AB";
const str2 = "CD";
printInterleavings(str1, str2);
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
OutputCDAB
CADB
ACDB
CABD
ACBD
ABCD
Time complexity: O(m * n * L), where m and n are the lengths of str1 and str2 respectively, and L is the average length of the interleaved strings.
Auxiliary Space: O(m * n * L), where m and n are the lengths of str1 and str2 respectively, and L is the average length of the interleaved strings.
Java Program to Print all Interleavings of given Two Strings
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem