Generate all possible strings such that char at index i is either str1[i] or str2[i]
Given two strings str1 and str2 each of length N, the task is to generate and print all possible strings of length N such that the character at index i of the generated string is either str1[i] or str2[i]
Examples:
Input: str1 = “abc”, str2 = “def”
Output:
abc
abf
aec
aef
dbc
dbf
dec
def
Input: str1 = “a”, str2 = “b”
Output:
a
b
Approach: The problem can be solved using recursion and at each recursive call, we need to select either the character at str1[i] or the character at str2[i] and append it to the resultant string. The termination condition will be when the length of the resultant string becomes equal to the length of the given strings.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void generateStr( char * a, char * b, string s,
int count, int len)
{
if (count == len) {
cout << s << endl;
return ;
}
generateStr(a + 1, b + 1, s + (*a),
count + 1, len);
generateStr(a + 1, b + 1, s + (*b),
count + 1, len);
}
int main()
{
char *a = "abc" , *b = "def" ;
int n = strlen (a);
generateStr(a, b, "" , 0, n);
return 0;
}
|
Java
class GFG
{
public static void generateStr(String a, String b,
String s, int count, int len)
{
if (count == len)
{
System.out.println(s);
return ;
}
generateStr(a.substring( 1 ), b.substring( 1 ),
s + a.charAt( 0 ), count + 1 , len);
generateStr(a.substring( 1 ), b.substring( 1 ),
s + b.charAt( 0 ), count + 1 , len);
}
public static void main(String[] args)
{
String a = "abc" , b = "def" ;
int n = a.length();
generateStr(a, b, "" , 0 , n);
}
}
|
Python3
def generateStr(a, b, s, count, len ):
if (count = = len ):
print (s);
return ;
generateStr(a[ 1 :], b[ 1 :],
s + a[ 0 ], count + 1 , len );
generateStr(a[ 1 :], b[ 1 :],
s + b[ 0 ], count + 1 , len );
a = "abc" ; b = "def" ;
n = len (a);
generateStr(a, b, "", 0 , n);
|
C#
using System;
class GFG
{
public static void generateStr(String a, String b,
String s, int count,
int len)
{
if (count == len)
{
Console.WriteLine(s);
return ;
}
generateStr(a.Substring(1), b.Substring(1),
s + a[0], count + 1, len);
generateStr(a.Substring(1), b.Substring(1),
s + b[0], count + 1, len);
}
public static void Main(String[] args)
{
String a = "abc" , b = "def" ;
int n = a.Length;
generateStr(a, b, "" , 0, n);
}
}
|
Javascript
<script>
function generateStr( a, b, s, count, len )
{
if (count == len)
{
document.write(s + "<br>" );
return ;
}
generateStr(a.substring(1), b.substring(1),
s + a[0], count + 1, len);
generateStr(a.substring(1), b.substring(1),
s + b[0], count + 1, len);
}
var a = "abc" , b = "def" ;
var n = a.length;
generateStr(a, b, "" , 0, n);
</script>
|
Output:
abc
abf
aec
aef
dbc
dbf
dec
def
Time Complexity: O(n)
Auxiliary Space: O(n) // due to recursive call stack
Last Updated :
28 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...