

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Longest Common Subsequence
Problem:
Let
x
1 x 2 ...
x
m
and
y
1 y 2 ...
y
n
be two sequences over some alphabet. (We
subsequence (LCS) ofassume they are strings of characters.) Find a longest common
x
1 x 2 ...
x
m
and
y
1 y 2 ...
y
n .
Example:
x
1 x
2 x
3 x 4 x 5 x
6 x
7 x
8
b a c b f f c b
y
1 y
2 y
3 y 4 y 5 y
6 y
7 y
8 y 9
d a b e a b f b c
z 1 z
2 z 3 z 4 z
5
b a b f c
is an LCS (shown below).
Subproblems:
Find an LCS of
x
1 x
2 ...
x i
and
y
1 y
2 ...
y
j
i
≤
m
j
≤
m
Optimal substructure:
If
z
=
z 1 z 2 ...
z
p
is a LCS of
x
1 x
2 ...
x
m
and
y
1 y
2 ...
y
n , then at
least one of these most hold.
i)
x
m
y
n , and
z 1 z 2 ...
z
p
is an LCS of
x
1 x
2 ...
x m
and
y
1 y
2 (^) ...
y n
ii)
x
m
y
n , and
z 1 z
2 ...
z p
is an LCS of
x
1 x
2 ...
x
m
and
y
1 y
2 ...
y
n ,
iii)
x
m
y
n , and
z 1 z 2 ...
z p
is an LCS of
x 1 x
2 ...
x
m
and
y 1 y
2 ...
y
n
Let
c
ij
= length of LCS of
x
1 x
2 ...
x i
and
y
y
1 y
2 ...
y j .
if
i
= 0 or
j
= 0,
c
[ i,j
c
[ i
, j
–1]
if
x
i
=
y j ,
max(
c
[ i
, j
] ,
c
[ i, j
if
x
i
≠
y
j .
if
x
i
=
y j ,
b
[ i,j
if
x
i
≠
y
j
and
c
[ i
, j
]
≥
c [ i, j
if
x
i
≠
y
j
and
c
[ i
, j
]
<
c
[ i, j
We compute the
c
[ i,j
] and
b
[ i,j
] in order of increasing
i
j , or alternatively in
order of increasing
i , and for a fixed
i , in order of increasing
j .
Example:
x
1 x 2 x
3 x
4 x
5 x
6 x 7 x
8
b a c b f f c b
y
1 y 2 y
3 y
4 y
5 y
6 y 7 y
8 y
9
d a b e a b f b c
Row
i , column
j
of the table below contains the value of
c [ i , (^) j ] followed
(except when
i
= 0 or
j
= 0) by that of
b
[ i , (^) j ]
d 1
a 2
b 3
e^4
a 5
b 6
f^7
b 8
c^9
b
↑
←
↑
←
↑
←
a
↑
↑
←
←
←
←
c
↑
b
↑
←
↑
←
↑
f
↑
←
←
f
↑
c
↑
b
↑
↑
↑
takes We can compute each table element in constant time, so the entire table
mn
) time.
following the arrows backward.We can write down an LCS by starting in the lower right corner and
Whenever we reach a square containing a "
↑
", say in row
i
and
column
j , we insert the character
x i
=
y j
at the beginning of the
subsequence.
d 1
a 2
b 3
e^4
a 5
b 6
f^7
b 8
c^9
b
↑
←
↑
←
↑
←
a
↑
↑
←
←
←
←
c
↑
b
↑
←
↑
←
↑
f
↑
←
←
f
↑
c
↑
b
↑
↑
↑
An LCS is
x
1 x
2 x 4 x 5 x
7
=
y 3 y
5 y
6 y
7 y
9
=
b a b f c
This computation takes
m
n
) time.