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 be a finite alphabet. A string is a finite sequence of symbols; is the empty string.
- Prefix , , with .
- Suffix , .
- Substring for (contiguous symbols).
- Subsequence: a string for which there are strictly increasing indices with . The indices realize in ; the same may have several index sequences.
Example. , : is a subsequence of , realized by and by , but it is not a substring. Every substring is a subsequence, not conversely.
How many. Substrings are : . Subsequences are far more: if all symbols of are distinct, every subset of indices gives a distinct subsequence, so there are . Enumerating the subsequences of and testing them on is therefore exponential.
The problem
Definition (LCS). Given and , find a string of maximum length that is a subsequence of both.
Example. , : an LCS is , of length , realized in by and in by . The LCS length measures the similarity of two strings (genomics, spell checking). It need not be unique: and have two LCS of length , and ; we look for one.
Optimal substructure
Idea: look at the last symbol. If and 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 : a quadratic space, not exponential like subsequences.
Theorem (LCS substructure). Let , be prefixes and an LCS of and .
- If or , then .
- If and :
- (a) if , then and is an LCS of and ;
- (b) if , then is an LCS of or of , hence the longer of the two.
Proof. Point 1 is trivial.
Case (a), . Let and realize in and .
- . Suppose not (or ). Then and , so is a common subsequence (indices and ) longer than : contradiction.
- is an LCS of and . All indices are , and likewise in , so is a common subsequence of and . If a longer common subsequence of and existed, would be a common subsequence of and longer than (cut-and-paste), a contradiction.
Case (b), . cannot equal both and . If (or ), index is unused, so is a common subsequence of and ; if , is a common subsequence of and . At least one holds. In the first case must be an LCS of (a longer one would also be common to and and beat ); in the second, of . Both such LCS are common subsequences of and , so none is longer than : is the longer of the two.
Cost recurrence and additional information
Let . For and :
Additional information. In base cases the solution is : nothing to store. Otherwise there are three ways to build : , or , or . Remember which one with an arrow : if , if , if .
Bottom-up code
Two tables and . Cell depends only on , , . Row and column hold the base cases; both row-by-row and column-by-column scans are consistent, since the three cells precede .
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:
Reconstruction. Start from and follow the arrows: at each step decreases by at least , so there are 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
, . Bold marks the reconstruction path from . Each cell shows and .
| A | D | C | C | B | D | ||
|---|---|---|---|---|---|---|---|
| 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: : , so , arrow . : , so . : , , tie, and the in the code picks .
Reconstruction: prints (after), prints , goes to prints , then , , , prints . Read top to bottom: , so .
The result depends on the tie-breaking rule: for and cell has ; with the code chooses and yields , choosing would yield .
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 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 and two calls:
Lower bound by unrolling. With : ( is non-decreasing in each argument), so and with : .
Exact value: . By induction on : if or the value is . Otherwise, with Pascal's rule,
For this is nodes against table cells. The cause is repeated subinstances: the same pair is reached by many paths.
Saving space
If only the length is needed, table is not required and needs only two rows: row depends only on row and on itself. Choosing gives space instead of .
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 , correct because . Base-case cells hold .
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 , , call is an internal node at most once, with unit cost (one comparison); other occurrences return the table value. So , the same as bottom-up.
- Not always all cells. For similar strings the top-down descent touches few cells. Example: , : calls , descending the diagonal while the last symbols agree (, then , then ) down to the base case . Only internal nodes against cells of bottom-up. In genomics, where sequences are almost equal, the gain is large. For the pair , the memoized code computes cells out of (dissimilar strings: small gain).
Typical exam questions
- For and , compute . Answer: .
- For , how many comparisons does
LCSperform, and how many internal nodes at most does pure D&C have? Answer: ; . - If , why does end with this symbol? Answer: otherwise appending the common symbol gives a longer common subsequence (indices and because ).
Versione ripasso
- Definitions. Prefix , suffix , substring (contiguous), subsequence (increasing indices, may have several realizations). Substrings ; subsequences of a string with distinct symbols . is a subsequence of (indices ) but not a substring.
- LCS: common subsequence of maximum length; similarity measure. and have LCS . Not unique ( and for , ).
- Theorem ( an LCS of ). (1) or : . (2a) : and is an LCS of . (2b) : is the longer of LCS and LCS. Proof by contradiction and cut-and-paste.
- Recurrence: if ; if ; otherwise. Arrow .
- Bottom-up: tables , with cells, row and column zero, then by rows (or columns). Cost comparisons.
PRINT_LCSfollows arrows in calls and prints the symbol after the recursive call on .
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 , : ; path prints , , , , then , , , .
- Pure D&C: (zero if or ); ; exact (Pascal): nodes for against cells.
- Space: only the length: two rows, (with ); reconstruction needs the whole table.
- Memoization: sentinel (); at most internal nodes, one per cell; far fewer on similar strings (, : only against cells). Worst case , 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: , : ; comparisons for : ; D&C internal nodes: .
- Typical mistakes: confusing substring and subsequence; initializing row and column with something other than ; adding when ; keeping one row and then trying to reconstruct; analyzing the memoized code with the D&C recurrence.