Shortest possible combination of two strings
Compute the shortest string for a combination of two given strings such that the new string consist of both the strings as its subsequences.
Input : a = "pear" b = "peach" Output : pearch pearch is the shorted string such that both pear and peach are its subsequences. Input : a = "geek" b = "code" Output : gecodek
We have discussed a solution to find length of the shortest supersequence in below post.
Shortest Common Supersequence
In this post, printing of supersequence is discussed. The solution is based on below recursive approach discussed in above post as an alternate method.
Let a[0..m-1] and b[0..n-1] be two strings and m and be respective lengths. if (m == 0) return n; if (n == 0) return m; // If last characters are same, then add 1 to // result and recur for a if (a[m-1] == b[n-1]) return 1 + SCS(a, b, m-1, n-1); // Else find shortest of following two // a) Remove last character from X and recur // b) Remove last character from Y and recur else return 1 + min( SCS(a, b, m-1, n), SCS(a, b, m, n-1) );
We build a DP array to store lengths. After building the DP array, we traverse from bottom right most position. The approach of printing is similar to printing LCS.
Time Complexity: O(m*n)
Auxiliary Space: O(m*n), where m = length of first string , n = length of second string.
Solution based on LCS:
We build the 2D array using LCS solution. If the character at the two pointer positions is equal, we increment the length by 1, else we store the maximum of the adjacent positions. Finally, we backtrack the matrix to find the index vector traversing which would yield the shortest possible combination.
Time Complexity : O(n2)
Auxiliary Space: O(n2)
This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.