Web Toolbar by Wibiya

Pages

Tuesday, March 20, 2012

Given two strings, print all interleaving strings.

Solution #1: Note that interleaving of two strings does not change the actual order of the characters within the two strings. For e.g.

str1 = "AB"
str2 = "MN"

So, in the output string, 'A' will always come before 'B' and 'M' will always come before 'N' .

Interleaving strings are,

ABMN
AMBN
AMNB
MABN
MANB
MNAB

void interleave(char* str1, char* str2, char* str, int len)
{
    int i=0;

    //if both input strings reach null, print final string and return
    if(str1[0] == '\0' && str2[0] == '\0')
    {
        printf("%s\n", str-len);
        return;
    }

    if(str1[0] != '\0')
    {
        str[0] = str1[0];
        interleave(str1+1, str2, str+1, len);
    }
    if(str2[0] != '\0')
    {
        str[0] = str2[0];
        interleave(str1, str2+1, str+1, len);
    }
}

int main()
{
    char* str1 = "AB";
    char* str2 = "MNO";

    //get length of input strings
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    int len = len1+len2;

    //allocate memory for output string
    char* str = (char*)malloc(len+1);
    memset(str, 0, len+1);

    interleave(str1, str2, str, len);
    return 0;
}

7 comments:

megha said...

i didn't get it..can u pls explain wd example??

Suchit Maindola said...

Hi Megha, if you did not understand what interleaving strings are.. then I have added a little more explanation to the post. Is the above example not clear? Please let me know if you understand it now.

But, if you did not understand the code then I can try to describe what it is doing. Let me know.

megha said...

i know what is interleaving...but not able to understand how this code generating all possible strings..I get stuck after traversing ABMN...

Suchit Maindola said...

think like this… there are two recursive calls to 'interleave' in the recursive function.. let's call them '1' and '2'.. call '1' is blocked as soon as 'str1' ends and similarly call '2' is blocked as soon as 'str2' ends… when both calls are made twice we exhaust both the strings and we return printing the output 'str'…

this is the recursive call sequence,

1122 => ABMN
1212 => AMBN
1221 => AMNB
2112 => MABN
2121 => MANB
2211 => MNAB

I know it is not easy to imagine a recurrence. I just couldn't think of a better way to explain.

Prasanna Kumar Nagasamudram said...

where is "int i" used ?

how does paramter "n" gets used ?

as a first case niether of the strings have '\0', so the function just returns and there is no recusion.

How is this working ?

Prasanna Kumar Nagasamudram said...

I meant where is paramter len used(not n)

Prasanna Kumar Nagasamudram said...

Oops my bad....I read

if(str1[0] != '\0')
as
if(str1[0] == '\0')
and
if(str2[0] != '\0')
as
if(str2[0] == '\0')

Its working perfectly fine.