LCS Example
LCS Example
we have two strings X=BACDB and Y=BDCB , find the longest common subsequence.
First step: Initially create a 2D matrix (say dp[][]) of size 8 x 7 whose first row and first column are filled with
0.
Third step: While traversed for i = 2, S1[1] and S2[0] are the same (both are ‘G’). So the dp value in that cell is
updated. Rest of the elements are updated as per the conditions.
Fifth step: For i = 4, we can see that S1[3] and S2[2] are same. So dp[4][3] updated as dp[3][2] + 1 = 2.
Filling row 4
Sixth step: Here we can see that for i = 5 and j = 5 the values of S1[4] and S2[4] are same (i.e., both are ‘A’).
So dp[5][5] is updated accordingly and becomes 3.
Filling row 5
Final step: For i = 6, see the last characters of both strings are same (they are ‘B’). Therefore the value of
dp[6][7] becomes 4.
In this procedure, table C[m, n] is computed in row major order and another table B[m,n] is computed to
construct optimal solution.