# Print all interleavings of given two strings in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two string str1 and str2 and we have to print all interleaving strings from both the string.

Interleaving string created using two given strings such that the order of characters of each string.

Let’s take an example to understand the problem −

Input: str1 = “XY” str2= “NS”
Output: XYNS, XNYS, XNSY, NXYS, NXSY, NSXY

To solve this problem, we will take all the characters in the strings. Length of str1 = m and length of str2 = n so we will create all interleaved strings from these strings.

For printing all interleaving strings, we will fix characters of strings and recursively call for all combinations of the string.

## Example

Implementation of our logic −

Live Demo

#include <iostream>
#include <string.h>
using namespace std;
void printStrings (char *str1, char *str2, char *iStr, int m, int n, int i) {
if (m == 0 && n == 0)
cout<<iStr<<endl ;
if (m != 0) {
iStr[i] = str1;
printStrings(str1 + 1, str2, iStr, m - 1, n, i + 1);
}
if (n != 0) {
iStr[i] = str2;
printStrings(str1, str2 + 1, iStr, m, n - 1, i + 1);
}
}
void generateInterleavingString(char *str1, char *str2, int m, int n) {
char *iStr= new char[((m + n + 1)*sizeof(char))];
iStr[m + n] ='\0';
printStrings(str1, str2, iStr, m, n, 0);
}
int main() {
char str1[] = "XY";
char str2[] = "NS";
cout<<"All interleaving string are :\n";
generateInterleavingString(str1, str2, strlen(str1), strlen(str2));
return 0;
}

## Output

All interleaving string is −
XYNS
XNYS
XNSY
NXYS
NXSY
NSXY