Salta al contenuto
Note per Studenti Longest Common Subsequence Report

Longest Common Subsequence

In questa pagina 9

The LCS is the second major example of Dynamic Programming - Paradigm and Memoizationdynamic programming improves on divide and conquer by storing the solutions of repeated subinstances in a table; Fibonacci shows the gap (F_n - 1 additions recursively, n - 1 with a table), memoization is recursion plus a global table, and optimization problems follow a five-step scheme built on optimal substructure and cut-and-paste.Dynamic Programming - Paradigm and Memoization → and the model of all string problems that follow.

Strings, prefixes, substrings, subsequences

Let Σ\Sigma be a finite alphabet. A string is a finite sequence X=⟨x1,…,xm⟩X = \langle x_1, \dots, x_m \rangle of symbols; ε\varepsilon is the empty string.

  • Prefix Xi=⟨x1,…,xi⟩X_i = \langle x_1, \dots, x_i \rangle, 0≤i≤m0 \le i \le m, with X0=εX_0 = \varepsilon.
  • Suffix Xi=⟨xi,…,xm⟩X^i = \langle x_i, \dots, x_m \rangle, 1≤i≤m+11 \le i \le m + 1.
  • Substring Xi..j=⟨xi,…,xj⟩X_{i..j} = \langle x_i, \dots, x_j \rangle for 1≤i≤j≤m1 \le i \le j \le m (contiguous symbols).
  • Subsequence: a string Z=⟨z1,…,zk⟩Z = \langle z_1, \dots, z_k \rangle for which there are strictly increasing indices 1≤j1<j2<⋯<jk≤m1 \le j_1 < j_2 < \dots < j_k \le m with zs=xjsz_s = x_{j_s}. The indices realize ZZ in XX; the same ZZ may have several index sequences.

Example. X=⟨A,B,C,B,B,D⟩X = \langle A, B, C, B, B, D \rangle, Z=⟨A,C,B⟩Z = \langle A, C, B \rangle: ZZ is a subsequence of XX, realized by ⟨1,3,4⟩\langle 1, 3, 4 \rangle and by ⟨1,3,5⟩\langle 1, 3, 5 \rangle, but it is not a substring. Every substring is a subsequence, not conversely.

How many. Substrings are Θ(m2)\Theta(m^2): 1+∑j=1m(m−j+1)=1+m(m+1)21 + \sum_{j=1}^{m}(m - j + 1) = 1 + \frac{m(m+1)}{2}. Subsequences are far more: if all symbols of XX are distinct, every subset of indices gives a distinct subsequence, so there are ∑k=0m(mk)=2m\sum_{k=0}^{m} \binom{m}{k} = 2^m. Enumerating the subsequences of XX and testing them on YY is therefore exponential.

The problem

Definition (LCS). Given X=⟨x1,…,xm⟩X = \langle x_1, \dots, x_m \rangle and Y=⟨y1,…,yn⟩Y = \langle y_1, \dots, y_n \rangle, find a string ZZ of maximum length that is a subsequence of both.

Example. X=⟨A,B,C,B,B,D⟩X = \langle A, B, C, B, B, D \rangle, Y=⟨A,D,C,C,B,D⟩Y = \langle A, D, C, C, B, D \rangle: an LCS is Z=⟨A,C,B,D⟩Z = \langle A, C, B, D \rangle, of length 44, realized in XX by ⟨1,3,4,6⟩\langle 1, 3, 4, 6 \rangle and in YY by ⟨1,4,5,6⟩\langle 1, 4, 5, 6 \rangle. The LCS length measures the similarity of two strings (genomics, spell checking). It need not be unique: ABCABC and BACBAC have two LCS of length 22, ⟨A,C⟩\langle A, C \rangle and ⟨B,C⟩\langle B, C \rangle; we look for one.

Optimal substructure

Idea: look at the last symbol. If XX and YY end with the same symbol it can always be matched; otherwise one of the two final symbols is unused. This reduces an instance to instances made of pairs of prefixes, of which there are (m+1)(n+1)=Θ(mn)(m + 1)(n + 1) = \Theta(mn): a quadratic space, not exponential like subsequences.

Theorem (LCS substructure). Let XiX_i, YjY_j be prefixes and Z=⟨z1,…,zk⟩Z = \langle z_1, \dots, z_k \rangle an LCS of XiX_i and YjY_j.

  1. If i=0i = 0 or j=0j = 0, then Z=εZ = \varepsilon.
  2. If i>0i > 0 and j>0j > 0:
    • (a) if xi=yjx_i = y_j, then zk=xi=yjz_k = x_i = y_j and Zk−1Z_{k-1} is an LCS of Xi−1X_{i-1} and Yj−1Y_{j-1};
    • (b) if xi≠yjx_i \ne y_j, then ZZ is an LCS of Xi−1,YjX_{i-1}, Y_j or of Xi,Yj−1X_i, Y_{j-1}, hence the longer of the two.

Proof. Point 1 is trivial.

Case (a), xi=yjx_i = y_j. Let i1<⋯<ik≤ii_1 < \dots < i_k \le i and j1<⋯<jk≤jj_1 < \dots < j_k \le j realize ZZ in XiX_i and YjY_j.

  • zk=xiz_k = x_i. Suppose not (or k=0k = 0). Then ik<ii_k < i and jk<jj_k < j, so ⟨Z,xi⟩\langle Z, x_i \rangle is a common subsequence (indices i1<⋯<ik<ii_1 < \dots < i_k < i and j1<⋯<jk<jj_1 < \dots < j_k < j) longer than ZZ: contradiction.
  • Zk−1Z_{k-1} is an LCS of Xi−1X_{i-1} and Yj−1Y_{j-1}. All indices i1<⋯<ik−1i_1 < \dots < i_{k-1} are ≤i−1\le i - 1, and likewise in YY, so Zk−1Z_{k-1} is a common subsequence of Xi−1X_{i-1} and Yj−1Y_{j-1}. If a longer common subsequence WW of Xi−1X_{i-1} and Yj−1Y_{j-1} existed, ⟨W,xi⟩\langle W, x_i \rangle would be a common subsequence of XiX_i and YjY_j longer than ZZ (cut-and-paste), a contradiction.

Case (b), xi≠yjx_i \ne y_j. zkz_k cannot equal both xix_i and yjy_j. If zk≠xiz_k \ne x_i (or k=0k = 0), index ii is unused, so ZZ is a common subsequence of Xi−1X_{i-1} and YjY_j; if zk≠yjz_k \ne y_j, ZZ is a common subsequence of XiX_i and Yj−1Y_{j-1}. At least one holds. In the first case ZZ must be an LCS of (Xi−1,Yj)(X_{i-1}, Y_j) (a longer one would also be common to XiX_i and YjY_j and beat ZZ); in the second, of (Xi,Yj−1)(X_i, Y_{j-1}). Both such LCS are common subsequences of XiX_i and YjY_j, so none is longer than ZZ: ZZ is the longer of the two. □\square

Cost recurrence and additional information

Let ℓ(i,j)=∣LCS(Xi,Yj)∣\ell(i, j) = |\text{LCS}(X_i, Y_j)|. For 0≤i≤m0 \le i \le m and 0≤j≤n0 \le j \le n:

ℓ(i,j)={0i=0 ∨ j=01+ℓ(i−1,j−1)i,j>0 ∧ xi=yjmax⁡{ℓ(i−1,j), ℓ(i,j−1)}i,j>0 ∧ xi≠yj\ell(i, j) = \begin{cases} 0 & i = 0 \ \lor \ j = 0 \\ 1 + \ell(i-1, j-1) & i, j > 0 \ \land \ x_i = y_j \\ \max\{\ell(i-1, j),\ \ell(i, j-1)\} & i, j > 0 \ \land \ x_i \ne y_j \end{cases}

Additional information. In base cases the solution is ε\varepsilon: nothing to store. Otherwise there are three ways to build ZZ: ⟨LCS(Xi−1,Yj−1),xi⟩\langle \text{LCS}(X_{i-1}, Y_{j-1}), x_i \rangle, or LCS(Xi,Yj−1)\text{LCS}(X_i, Y_{j-1}), or LCS(Xi−1,Yj)\text{LCS}(X_{i-1}, Y_j). Remember which one with an arrow b(i,j)b(i,j): ↖\nwarrow if xi=yjx_i = y_j, ←\leftarrow if Z=LCS(Xi,Yj−1)Z = \text{LCS}(X_i, Y_{j-1}), ↑\uparrow if Z=LCS(Xi−1,Yj)Z = \text{LCS}(X_{i-1}, Y_j).

Bottom-up code

Two tables ℓ[0..m,0..n]\ell[0..m, 0..n] and b[0..m,0..n]b[0..m, 0..n]. Cell (i,j)(i, j) depends only on (i−1,j−1)(i-1, j-1), (i−1,j)(i-1, j), (i,j−1)(i, j-1). Row 00 and column 00 hold the base cases; both row-by-row and column-by-column scans are consistent, since the three cells precede (i,j)(i, j).

LCS(X, Y)
  m <- |X|; n <- |Y|
  for i <- 0 to m do l[i, 0] <- 0
  for j <- 1 to n do l[0, j] <- 0
  for i <- 1 to m do
    for j <- 1 to n do
      if x_i = y_j then
        l[i, j] <- 1 + l[i-1, j-1]
        b[i, j] <- '↖'
      else if l[i-1, j] >= l[i, j-1] then
        l[i, j] <- l[i-1, j]
        b[i, j] <- '↑'
      else
        l[i, j] <- l[i, j-1]
        b[i, j] <- '←'
  return (l[m, n], b)

Cost. Counting comparisons between symbols, one per iteration:

T(m,n)=∑i=1m∑j=1n1=m⋅n=Θ(mn).T(m, n) = \sum_{i=1}^{m} \sum_{j=1}^{n} 1 = m \cdot n = \Theta(mn).

Reconstruction. Start from (m,n)(m, n) and follow the arrows: at each step i+ji + j decreases by at least 11, so there are O(m+n)O(m + n) calls.

PRINT_LCS(X, b, i, j)               { first call: PRINT_LCS(X, b, m, n) }
  if i = 0 or j = 0 then return
  if b[i, j] = '↖' then
    PRINT_LCS(X, b, i-1, j-1)       { first the LCS of the prefixes... }
    print(x_i)                      { ...then the common symbol }
  else if b[i, j] = '←' then PRINT_LCS(X, b, i, j-1)
  else PRINT_LCS(X, b, i-1, j)

Worked example

X=⟨A,B,C,B,B,D⟩X = \langle A, B, C, B, B, D \rangle, Y=⟨A,D,C,C,B,D⟩Y = \langle A, D, C, C, B, D \rangle. Bold marks the reconstruction path from (6,6)(6, 6). Each cell shows ℓ(i,j)\ell(i, j) and b(i,j)b(i, j).

ε\varepsilon A D C C B D
ε\varepsilon 0 0 0 0 0 0 0
A 0 1↖ 1← 1← 1← 1← 1←
B 0 1↑ 1↑ 1↑ 1↑ 2↖ 2←
C 0 1↑ 1↑ 2↖ 2↖ 2↑ 2↑
B 0 1↑ 1↑ 2↑ 2↑ 3↖ 3←
B 0 1↑ 1↑ 2↑ 2↑ 3↖ 3↑
D 0 1↑ 2↖ 2↑ 2↑ 3↑ 4↖

Some cells by hand: (1,1)(1, 1): x1=y1=Ax_1 = y_1 = A, so ℓ=1+ℓ(0,0)=1\ell = 1 + \ell(0, 0) = 1, arrow ↖\nwarrow. (2,5)(2, 5): x2=y5=Bx_2 = y_5 = B, so ℓ=1+ℓ(1,4)=2\ell = 1 + \ell(1, 4) = 2. (4,4)(4, 4): x4=B≠C=y4x_4 = B \ne C = y_4, ℓ(3,4)=ℓ(4,3)=2\ell(3, 4) = \ell(4, 3) = 2, tie, and the ≥\ge in the code picks ↑\uparrow.

Reconstruction: (6,6) ↖(6,6)\ \nwarrow prints DD (after), (5,5) ↖(5,5)\ \nwarrow prints BB, (4,4) ↑(4,4)\ \uparrow goes to (3,4) ↖(3,4)\ \nwarrow prints CC, then (2,3) ↑(2,3)\ \uparrow, (1,3) ←(1,3)\ \leftarrow, (1,2) ←(1,2)\ \leftarrow, (1,1) ↖(1,1)\ \nwarrow prints AA. Read top to bottom: A,C,B,DA, C, B, D, so ℓ(6,6)=4\ell(6, 6) = 4.

The result depends on the tie-breaking rule: for ABCABC and BACBAC cell (2,2)(2, 2) has ℓ(1,2)=ℓ(2,1)=1\ell(1, 2) = \ell(2, 1) = 1; with ≥\ge the code chooses ↑\uparrow and yields ⟨A,C⟩\langle A, C \rangle, choosing ←\leftarrow would yield ⟨B,C⟩\langle B, C \rangle.

python
def lcs(X, Y):
    m, n = len(X), len(Y)
    l = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if X[i - 1] == Y[j - 1]:
                l[i][j] = 1 + l[i - 1][j - 1]
            else:
                l[i][j] = max(l[i - 1][j], l[i][j - 1])
    i, j, z = m, n, []
    while i > 0 and j > 0:                  # reconstruction without table b
        if X[i - 1] == Y[j - 1]:
            z.append(X[i - 1]); i -= 1; j -= 1
        elif l[i - 1][j] >= l[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return l[m][n], "".join(reversed(z))

assert lcs("ABCBBD", "ADCCBD") == (4, "ACBD")

The table bb may be omitted: the arrow is recovered afterwards by comparing neighbouring cells, as the loop above does.

Divide and conquer on the same recurrence

A recursive algorithm on the same substructure, in the worst case (e.g. no common symbols), has one internal node of unit work for every pair with m,n>0m, n > 0 and two calls:

T(m,n)={0m=0 ∨ n=0T(m−1,n)+T(m,n−1)+1otherwiseT(m, n) = \begin{cases} 0 & m = 0 \ \lor \ n = 0 \\ T(m-1, n) + T(m, n-1) + 1 & \text{otherwise} \end{cases}

Lower bound by unrolling. With m=nm = n: T(n,n)≥2T(n−1,n−1)+1T(n, n) \ge 2T(n-1, n-1) + 1 (TT is non-decreasing in each argument), so T(n,n)≥2iT(n−i,n−i)+2i−1T(n, n) \ge 2^i T(n-i, n-i) + 2^i - 1 and with i=ni = n: T(n,n)≥2n−1T(n, n) \ge 2^n - 1.

Exact value: T(m,n)=(m+nm)−1T(m, n) = \binom{m+n}{m} - 1. By induction on m+nm + n: if m=0m = 0 or n=0n = 0 the value is 00. Otherwise, with Pascal's rule,

T(m,n)=[(m+n−1m−1)−1]+[(m+n−1m)−1]+1=(m+nm)−1.T(m, n) = \Big[\tbinom{m+n-1}{m-1} - 1\Big] + \Big[\tbinom{m+n-1}{m} - 1\Big] + 1 = \tbinom{m+n}{m} - 1.

For m=n=20m = n = 20 this is (4020)−1=137 846 528 819\binom{40}{20} - 1 = 137\,846\,528\,819 nodes against 400400 table cells. The cause is repeated subinstances: the same pair (i,j)(i, j) is reached by many paths.

Saving space

If only the length is needed, table bb is not required and ℓ\ell needs only two rows: row ii depends only on row i−1i - 1 and on itself. Choosing ∣Y∣≤∣X∣|Y| \le |X| gives space Θ(min⁡{m,n})\Theta(\min\{m, n\}) instead of Θ(mn)\Theta(mn).

LCS_LENGTH(X, Y)                    { |Y| <= |X| }
  m <- |X|; n <- |Y|
  for j <- 0 to n do prev[j] <- 0
  for i <- 1 to m do
    curr[0] <- 0
    for j <- 1 to n do
      if x_i = y_j then curr[j] <- 1 + prev[j-1]
      else curr[j] <- max(prev[j], curr[j-1])
    prev <- curr
  return prev[n]

With reconstruction the whole table must be kept.

The memoized algorithm

Keep the recursion and add the global table. The sentinel is −1-1, correct because ℓ≥0\ell \ge 0. Base-case cells hold 00.

INIT_LCS(X, Y)
  m <- |X|; n <- |Y|
  if m = 0 or n = 0 then return 0
  for i <- 0 to m do l[i, 0] <- 0
  for j <- 0 to n do l[0, j] <- 0
  for i <- 1 to m do
    for j <- 1 to n do l[i, j] <- -1
  return MEMO_LCS(X, Y, m, n)

MEMO_LCS(X, Y, i, j)
  if l[i, j] = -1 then
    if x_i = y_j then
      l[i, j] <- 1 + MEMO_LCS(X, Y, i-1, j-1)
    else
      a <- MEMO_LCS(X, Y, i-1, j)
      c <- MEMO_LCS(X, Y, i, j-1)
      l[i, j] <- max(a, c)
  return l[i, j]
  • Worst-case cost: analyze the call tree. For 1≤i≤m1 \le i \le m, 1≤j≤n1 \le j \le n, call (i,j)(i, j) is an internal node at most once, with unit cost (one comparison); other occurrences return the table value. So T(m,n)≤m⋅nT(m, n) \le m \cdot n, the same as bottom-up.
  • Not always all cells. For similar strings the top-down descent touches few cells. Example: X=⟨A,A,B,B,C⟩X = \langle A, A, B, B, C \rangle, Y=⟨B,B,C⟩Y = \langle B, B, C \rangle: calls (5,3)→(4,2)→(3,1)→(2,0)(5,3) \to (4,2) \to (3,1) \to (2,0), descending the diagonal while the last symbols agree (C=CC = C, then B=BB = B, then B=BB = B) down to the base case (2,0)(2, 0). Only 33 internal nodes against 5×3=155 \times 3 = 15 cells of bottom-up. In genomics, where sequences are almost equal, the gain is large. For the pair ABCBBDABCBBD, ADCCBDADCCBD the memoized code computes 1616 cells out of 3636 (dissimilar strings: small gain).

Typical exam questions

  1. For X=⟨a,f,r,a⟩X = \langle a, f, r, a \rangle and Y=⟨a,f,a⟩Y = \langle a, f, a \rangle, compute l(2,2)+l(4,3)l(2, 2) + l(4, 3). Answer: 2+3=52 + 3 = 5.
  2. For m=n=10m = n = 10, how many comparisons does LCS perform, and how many internal nodes at most does pure D&C have? Answer: mn=100mn = 100; (2010)−1=184 755\binom{20}{10} - 1 = 184\,755.
  3. If xi=yjx_i = y_j, why does LCS(Xi,Yj)\text{LCS}(X_i, Y_j) end with this symbol? Answer: otherwise appending the common symbol gives a longer common subsequence (indices ik<ii_k < i and jk<jj_k < j because zk≠xi,yjz_k \ne x_i, y_j).

Versione ripasso

  • Definitions. Prefix XiX_i, suffix XiX^i, substring Xi..jX_{i..j} (contiguous), subsequence (increasing indices, may have several realizations). Substrings 1+m(m+1)/2=Θ(m2)1 + m(m+1)/2 = \Theta(m^2); subsequences of a string with distinct symbols ∑k(mk)=2m\sum_k \binom{m}{k} = 2^m. ⟨A,C,B⟩\langle A,C,B \rangle is a subsequence of ABCBBDABCBBD (indices 1,3,41,3,4) but not a substring.
  • LCS: common subsequence of maximum length; similarity measure. ABCBBDABCBBD and ADCCBDADCCBD have LCS ⟨A,C,B,D⟩\langle A,C,B,D \rangle. Not unique (ACAC and BCBC for ABCABC, BACBAC).
  • Theorem (ZZ an LCS of Xi,YjX_i, Y_j). (1) i=0i = 0 or j=0j = 0: Z=εZ = \varepsilon. (2a) xi=yjx_i = y_j: zk=xiz_k = x_i and Zk−1Z_{k-1} is an LCS of (Xi−1,Yj−1)(X_{i-1}, Y_{j-1}). (2b) xi≠yjx_i \ne y_j: ZZ is the longer of LCS(Xi−1,Yj)(X_{i-1}, Y_j) and LCS(Xi,Yj−1)(X_i, Y_{j-1}). Proof by contradiction and cut-and-paste.
  • Recurrence: ℓ(i,j)=0\ell(i,j) = 0 if i=0∨j=0i = 0 \lor j = 0; 1+ℓ(i−1,j−1)1 + \ell(i-1,j-1) if xi=yjx_i = y_j; max⁡{ℓ(i−1,j),ℓ(i,j−1)}\max\{\ell(i-1,j), \ell(i,j-1)\} otherwise. Arrow b(i,j)∈{↖,←,↑}b(i,j) \in \{\nwarrow, \leftarrow, \uparrow\}.
  • Bottom-up: tables ℓ\ell, bb with (m+1)(n+1)(m+1)(n+1) cells, row 00 and column 00 zero, then by rows (or columns). Cost T(m,n)=mnT(m,n) = mn comparisons. PRINT_LCS follows arrows in O(m+n)O(m+n) calls and prints the symbol after the recursive call on ↖\nwarrow.
LCS(X, Y)
  for i <- 0 to m do l[i, 0] <- 0;  for j <- 1 to n do l[0, j] <- 0
  for i <- 1 to m do for j <- 1 to n do
    if x_i = y_j then l[i,j] <- 1 + l[i-1,j-1]; b[i,j] <- '↖'
    else if l[i-1,j] >= l[i,j-1] then l[i,j] <- l[i-1,j]; b[i,j] <- '↑'
    else l[i,j] <- l[i,j-1]; b[i,j] <- '←'
  return (l[m,n], b)

PRINT_LCS(X, b, i, j)
  if i = 0 or j = 0 then return
  if b[i,j] = '↖' then PRINT_LCS(X,b,i-1,j-1); print(x_i)
  else if b[i,j] = '←' then PRINT_LCS(X,b,i,j-1)
  else PRINT_LCS(X,b,i-1,j)
  • Example X=ABCBBDX = ABCBBD, Y=ADCCBDY = ADCCBD: ℓ(6,6)=4\ell(6,6) = 4; path (6,6) ↖(6,6)\,\nwarrow prints DD, (5,5) ↖(5,5)\,\nwarrow BB, (4,4) ↑(4,4)\,\uparrow, (3,4) ↖(3,4)\,\nwarrow CC, then (2,3) ↑(2,3)\,\uparrow, (1,3) ←(1,3)\,\leftarrow, (1,2) ←(1,2)\,\leftarrow, (1,1) ↖(1,1)\,\nwarrow AA.
  • Pure D&C: T(m,n)=T(m−1,n)+T(m,n−1)+1T(m,n) = T(m-1,n) + T(m,n-1) + 1 (zero if m=0m = 0 or n=0n = 0); T(n,n)≥2n−1T(n,n) \ge 2^n - 1; exact (m+nm)−1\binom{m+n}{m} - 1 (Pascal): 137 846 528 819137\,846\,528\,819 nodes for m=n=20m = n = 20 against 400400 cells.
  • Space: only the length: two rows, Θ(min⁡{m,n})\Theta(\min\{m,n\}) (with ∣Y∣≤∣X∣|Y| \le |X|); reconstruction needs the whole table.
  • Memoization: sentinel −1-1 (ℓ≥0\ell \ge 0); at most mnmn internal nodes, one per cell; far fewer on similar strings (X=AABBCX = AABBC, Y=BBCY = BBC: only (5,3),(4,2),(3,1)(5,3), (4,2), (3,1) against 1515 cells). Worst case mnmn, as bottom-up.
MEMO_LCS(X, Y, i, j)                { l[0,*] = l[*,0] = 0, other cells = -1 }
  if l[i,j] = -1 then
    if x_i = y_j then l[i,j] <- 1 + MEMO_LCS(X,Y,i-1,j-1)
    else a <- MEMO_LCS(X,Y,i-1,j); c <- MEMO_LCS(X,Y,i,j-1); l[i,j] <- max(a,c)
  return l[i,j]
  • Typical questions: X=afraX = afra, Y=afaY = afa: l(2,2)+l(4,3)=2+3=5l(2,2) + l(4,3) = 2 + 3 = 5; comparisons for m=n=10m = n = 10: 100100; D&C internal nodes: (2010)−1=184 755\binom{20}{10} - 1 = 184\,755.
  • Typical mistakes: confusing substring and subsequence; initializing row and column 00 with something other than 00; adding 11 when xi≠yjx_i \ne y_j; keeping one row and then trying to reconstruct; analyzing the memoized code with the D&C recurrence.

Teoria collegata