Longest Common Subsequence 19
Longest Common Subsequence 19
LONGEST COMMON
SUBSEQUENCE
LONGEST COMMON SUBSEQUENCE
Given two strings, S1 and S2, the task is to
find the length of the Longest Common
Subsequence, i.e. longest subsequence
present in both of the strings
A longest common subsequence (LCS) is
Output: 2
The longest subsequence which is present in
both strings is “BD”.
RECURSIVE EQUATION
LCS ALGORITHM
Consider two strings:
X= a b a a b a
Y= b a b b a b
^ b a b b a b
^ 0 0 0 0 0 0 0
a 0
b 0
a 0
a 0
b 0
a 0
EXAMPLE
For index i=1, j=1
CONT…
For index i=1, j=2
CONT…
For index i=1, j=3
CONT…
For index i=1, j=4
CONT…
For index i=1, j=5
CONT…
For index i=1, j=6
CONT…
For index i=2, j=1
CONT…
In this way we find the complete table
The final table would be
LCS=4
In the above table, we can observe that all the entries are
filled. Now we are at the last cell having 4 value. This cell
moves at the left which contains 4 value.; therefore, the
first character of the LCS is 'a'
CONT…
The left cell moves upwards diagonally
whose value is 3; therefore, the next
character is 'b' and it becomes 'ba'. Now the
cell has 2 value that moves on the left. The
next cell also has 2 value which is moving
upwards; therefore, the next character is 'a'
and it becomes 'aba'.
The next cell is having a value 1 that moves