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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Printing Longest Common Subsequence | Set 2 (Printing All)
- Printing Longest Bitonic Subsequence
- Construction of Longest Increasing Subsequence(LIS) and printing LIS sequence
- Longest Common Subsequence | DP-4
- Longest Common Increasing Subsequence (LCS + LIS)
- Longest Common Anagram Subsequence
- Longest Common Subsequence with at most k changes allowed
- LCS (Longest Common Subsequence) of three strings
- C++ Program for Longest Common Subsequence
- Longest Common Subsequence | DP using Memoization
- Longest common anagram subsequence from N strings
- Edit distance and LCS (Longest Common Subsequence)
- Longest common subsequence with permutations allowed
- Length of longest common subsequence containing vowels
- Python Program for Longest Common Subsequence
- Java Program for Longest Common Subsequence
- Longest Subsequence with at least one common digit in every element
- Longest subsequence such that adjacent elements have at least one common digit
- Minimum cost to make Longest Common Subsequence of length k
- Printing Shortest Common Supersequence