Dynamic Programming Longest Common Subsequence
Dynamic Programming Longest Common Subsequence
A subsequence of a given sequence is the given sequence with just some elements left out
(order should be from left-to-right, not necessarily consecutive).. A common sequence of two
sequences X and Y, is a subsequence of both X and Y.A longest common subsequence is the one
with maximum length. For example, if X = {A,B,C,B,D,A,B} and Y = { B,D,C,A,B,A} then the
longest common subsequence is of length 4 and they are {B,C,B,A} and {B,D,A,B}.
Finding the longest common subsequence has applications in areas like biology. The longest
subsequence (LCS) problem has an optimal substructure property. Thus, dynamic programming
method can be used to solve this problem.
Theorem used - Let X =< x1, x2, . . . , xm > and Y =< y1, y2, . . . , yn > be sequences, and let Z
=< z1, z2, . . . , zk > be any LCS of X and Y .
1. If xm = yn, then zk = xm = yn and Zk1 is an LCS of Xm1 and Yn1.
2. If xm = yn, then zk = xm implies that Z is an LCS of Xm1 and Y.
3. If xm = yn, then zk = yn implies that Z is an LCS of X and Yn1.
Algorithm:
S,T are two strings for which we have to find the longest common sub sequence. Input the two
sequences. Now print the longest common subsequence using LongestCommonSubsequence function.
LongestCommonSubsequence function : This function takes the two sequences (S, T) as arguments and
returns the longest common subsequence found.
Store the length of both the subsequences. Slength = strlen(S), Tlength = strlen(T).
We will Start with the index from 1 for our convenience (avoids handling special cases for
negative indices).
Example:
j=4
B A, common[4][4] = max(common[4][3] , common[3][4]) = 2
common[4][4] = 2
Output: Longest common susequence is of length 2
An example: Xi = A B C B D A B and Yi = B D C A B A
i/j
Yj
0
0
Xi
2 B
3 C
4 B
5 D
6 A
To reconstruct the elements of an LCS, follow the matrix arrows from the lower right-hand
corner; the path is shaded. Each
on the path corresponds to an entry (highlighted) for
which Xi = Yi, is a member of LCS. The length of the common subsequence is 4.