Javatpoint Logo
Javatpoint Logo

Print all interleavings of given two strings in C++

In this article, we will discuss how to print all interleavings of the given two strings in C++. But before going through its implementation, we will know about the interleavings.

What are Interleavings?

Interleavings of two strings are formed by merging the characters of two strings in all possible ways while maintaining their relative order. For example, the interleavings of "AB" and "CD" are "ABCD", "ACBD", "ACDB", "CABD", "CADB", and "CDAB".

The problem of printing all possible interleavings of two given strings is a common recursion and dynamic programming problem.

Problem Statement

Given two strings, str1 and str2, print all possible interleavings of the two strings. An interleaved string preserves the order of characters in individual strings.

For example:

str1 = "AB"

str2 = "CD"

Possible Interleavings:

ABCD

ACBD

ACDB

CABD

CADB

CDAB

1. Naive Recursive Approach

A simple recursive solution is to generate all interleavings by choosing a character from either string at each step.

  • If str1is non-empty, recursively generate interleavings for str1[1...] and str2. Prepend str1[0] to result.
  • If str2is non-empty, recursively generate interleavings for str1 and str2[1...]. Prepend str2[0] to result.

Base cases:

  • If both strings are empty, print the generated interleaving.
  • If one string is empty, only choose characters from the non-empty string.

It gives us an exponential time complexity of O(2^n), where n is the length of the two strings.

Example:

Let's take an example to print all interleavings of given two strings in C++.

Output:

ABCD
ACBD
ACDB
CABD
CADB
CDAB

This recursively generates all valid interleavings in lexicographic order.

2. Dynamic Programming Approach

We can optimize it using a bottom-up dynamic programming approach.

  • Create a 2D matrix dp[m+1][n+1] to store the interleavings.
  • Fill up the matrix diagonally from empty strings to full strings.
  • To fill a cell dp[i][j]:
    1. Appendstr1[i-1] to interleavings of dp[i-1][j]
    2. Appendstr2[j-1] to interleavings of dp[i][j-1]
  • Final interleavings will be stored in dp[m][n].
  • It reduces the complexity to O(m*n) as we store the results instead of recomputing.

Example:

C++ code implementing Dynamic programming approach:

Output:

ABCD
ACBD
ACDB 
CABD
CADB
CDAB

This bottom-up DP approach avoids recomputation and improves efficiency over the recursive approach.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA