CSCE 411 Lecture 13

From Notes
Jump to navigation Jump to search
Lecture Slides

« previous | Monday, September 24, 2012 | next »


Longest Common Subsequence

Suppose you have a sequence X=x1,x2,,xm of elements over a finite set S.

A sequence Z=z1,z2,zk over S is called a subsequence of X iff it can be obtained from X by deleting elements.

Put differently, there exist indices i1<i2<<ik such that za=xia for all 1ak

For example, A,C,D,F is a subsequence of A,B,C,D,E,F


Suppose Y=y1,y2,,yn is also a sequence over S.

We call Z a common subsequence of X and Y iff it is a subsequence of X and a subsequence of Y

For example, A,C,D,F is a common subsequence of A,B,C,D,E,F and A,A,C,B,A,D,F.

Given two sequences X and Y over a set S, what is the longest common subsequence Z between them?


Naïve Solution: Brute Force

There are 2m subsequences of X. We could check every one of them, filtering them by whether they are subsequences of Y (this would take O(n) time), and then determine the longest one. Overall, this takes O(n2m) time.

Dynamic Approach

If X=x1,x2,,xm is a sequence, let Xi=x1,x2,,xi be the ith prefix of X such that 1im.


Let LCS(X,Y) be the longest common subsequence between X and Y.

Let X=x1,x2,,xm and Y=y1,y2,,yn. Let Z=z1,z2,,zk.

  1. If xm=yn, then certainly xm=yn=zk and Zk1 is in LCS(Xm1,Yn1).
  2. If xmyn, then xmzk implies that Z is in LCS(Xm1,Y).
  3. If xmyn, then ymzk implies that Z is in LCS(X,Yn1.

(2) and (3) indicate overlapping subproblems of choosing the larger common subsequence of each of the two cases.

Recursive Solution

Let Cij be the length of an element in LCS(Xi,Yj). Cij={0i=0j=0Ci1,j1+1i,j>0xi=yjmax(Ci,j1,Ci1,j)i,j>0xiyj

Dynamic Programming Solution

Start our C table by initializing the first row and column to 0 since the length of a common subsequence of [sequences of length 0] is 0.

Calculate C1j for 1jn.

Calculate C2j for 1jn. (etc.)

Return Cmn.

The complexity of computing this solution has been reduced to O(mn).

In computing Cij, this particular solution depends on the cells directly above, to the right, and diagonally from it.

Whenever we satisfy case (1), choosing the diagonal solution, we know that we have grabbed the ith element from the end of Xi.

Keep track of the direction toward the optimal solution chosen (up, left, or diagonal)

To reconstruct the solution, start in Cmn and follow arrows, taking Xi whenever Cij has a "diagonal pointer".

Example

For sequences X=A,B,C,B Y=B,D,C,A

  yj B D C A
xj 0 0 0 0 0
A 0 ↑ 0 ↑ 0 ↑ 0 ↖ 1
B 0 ↖ 1 ← 1 ← 1 ↑ 1
C 0 ↑ 1 ↑ 1 ↖ 2 ← 2
B 0 ↑ 1 ↑ 1 ↑ 2 ↑ 2

To construct the soluion, follow arrows and obtain "BC"