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 StatementGiven 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 ApproachA simple recursive solution is to generate all interleavings by choosing a character from either string at each step.
Base cases:
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 ApproachWe can optimize it using a bottom-up dynamic programming approach.
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. |