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.
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 minimum of the adjacent positions. Finally, we backtrack the matrix to find the index vector traversing which would yield the shortest possible combination.
This article is contributed by Raghav Jajodia. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.
- Check if a given string is sum-string
- Print all Subsequences of String which Start with Vowel and End with Consonant.
- Given two strings check which string makes a palindrome first
- Efficiently find first repeated character in a string without using any additional data structure in one traversal
- Maximum games played by winner
- Shortest Uncommon Subsequence
- Top 20 Dynamic Programming Interview Questions
- A Space Optimized Solution of LCS
- Find minimum number of coins that make a given value
- Shortest Common Supersequence
- Printing Longest Common Subsequence
- Optimal Strategy for a Game | DP-31
- Partition problem | DP-18
- Matrix Chain Multiplication | DP-8
- Longest Common Subsequence | DP-4