DYNAMIC PROGRAMING
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
defined as the longest subsequence which is
common in all given input sequences
CONT…
Input: S1 = “AGGTAB”, S2 = “GXTXAYB”
Output: 4
The longest subsequence which is present in
both strings is “GTAB”.
Input: S1 = “BD”, S2 = “ABCD”
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
upwards. Now we reach the cell (b, b) having
value which is moving diagonally upwards;
therefore, the next character is 'b'. The final
string of longest common subsequence is
'baba'.
TIME COMPLEXITY
o We have two nested loops
-The outer one iterate n times
-The inner one iterate m times
-Thus, total running time complexty is O(m * n)
Auxiliary Space: O(m) because the
algorithm uses two arrays of size m.
APPLICATION