Given two sequences, print the longest subsequence present in both of them.
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
We have discussed Longest Common Subsequence (LCS) problem in a previous post. The function discussed there was mainly to find the length of LCS. To find length of LCS, a 2D table L was constructed. In this post, the function to construct and print LCS is discussed.
Following is detailed algorithm to print the LCS. It uses the same 2D table L.
1) Construct L[m+1][n+1] using the steps discussed in previous post.
2) The value L[m][n] contains length of LCS. Create a character array lcs of length equal to the length of lcs plus 1 (one extra to store \0).
2) Traverse the 2D array starting from L[m][n]. Do following for every cell L[i][j]
…..a) If characters (in X and Y) corresponding to L[i][j] are same (Or X[i-1] == Y[j-1]), then include this character as part of LCS.
…..b) Else compare values of L[i-1][j] and L[i][j-1] and go in direction of greater value.
The following table (taken from Wiki) shows steps (highlighted) followed by the above algorithm.
Following is the implementation of above approach.
LCS of AGGTAB and GXTXAYB is GTAB
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Printing Longest Common Subsequence | Set 2 (Printing All)
- Printing Longest Bitonic Subsequence
- Longest Common Subsequence | DP-4
- LCS (Longest Common Subsequence) of three strings
- Longest Common Subsequence with at most k changes allowed
- Longest Common Anagram Subsequence
- Longest Common Subsequence | DP using Memoization
- Longest Common Increasing Subsequence (LCS + LIS)
- C++ Program for Longest Common Subsequence
- Python Program for Longest Common Subsequence
- Longest common anagram subsequence from N strings
- Java Program for Longest Common Subsequence
- Length of longest common subsequence containing vowels
- Longest common subsequence with permutations allowed
- Longest Subsequence with at least one common digit in every element
Improved By : Sam007