String Alignment and Longest Palindromic Subsequence
In questa pagina 3
Two applications of dynamic programming (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 →) that reuse the structure of the Longest Common Subsequencethe longest common subsequence of X (m symbols) and Y (n symbols) is found by dynamic programming on pairs of prefixes with l(i,j) = 0 if i = 0 or j = 0, 1 + l(i-1,j-1) if x_i = y_j, max of the two neighbours otherwise; bottom-up costs mn comparisons, reconstruction O(m+n), pure divide and conquer costs C(m+n,m) - 1 internal nodes, and space drops to Theta(min{m,n}) if only the length is needed.Longest Common Subsequence →: the first with the same subproblem space (pairs of prefixes), the second with a different one (substrings).
DNA string alignment
The DNA alphabet is ; for alignment it is extended with a space character, . The optimal cost is a similarity metric between the two strings.
Problem definition
Definition (alignment). Given and over , an alignment of length is a pair of strings , over , with , such that:
- is a subsequence of and is a subsequence of ;
- positions that do not realize symbols of (resp. ) contain only ;
- no position has two spaces: .
Each column of the alignment is of one of three types: symbol of over symbol of ; symbol of over a space; space over symbol of .
Example. , . Two alignments:
Z^X = A G T T Z^X = A G T T
Z^Y = A - T T Z^Y = A T T -Cost. A score matrix gives an integer for each ordered pair of nucleotides (usually symmetric, positive on the diagonal for matches, negative elsewhere); the gap penalty (usually negative) is the weight of a position with a space. The weight of a position and the cost of the alignment are
Optimal alignment problem. Given , and , find the maximum cost of an alignment of the two strings.
Example (continued). , for , . The first alignment costs ; the second . The first is optimal.
Optimal substructure
Once the ending of the two alignments is fixed, the rest is an alignment of prefixes: the subproblem space is that of the LCS, .
Base cases. If , the only feasible alignment of is spaces over (condition 3 forbids two spaces in a position), of cost . Symmetrically for the cost is ; for it is .
Non-base cases (, ). Let be an optimal alignment of , of length . The last position has only three possible types:
- and . Then the first positions are an optimal alignment of (otherwise cut-and-paste would give a better one) and .
- and . The first positions are an optimal alignment of and .
- and : symmetric, an optimal alignment of and .
The three alignments built from optima of the subproblems are all feasible, so the one of maximum cost wins.
Cost recurrence
With the cost of the optimal alignment of :
To rebuild the alignment, store an arrow as in the LCS: , or according to which term attains the maximum.
Bottom-up code
The dependency graph is identical to the LCS one, so the table is filled by rows.
ALIGN(X, Y, S, g)
m <- |X|; n <- |Y|
for i <- 0 to m do C[i, 0] <- i * g; b[i, 0] <- '↑' { b[0, 0] is never read }
for j <- 1 to n do C[0, j] <- j * g; b[0, j] <- '←'
for i <- 1 to m do
for j <- 1 to n do
d <- C[i-1, j-1] + S[x_i, y_j]
u <- C[i-1, j] + g
l <- C[i, j-1] + g
C[i, j] <- max(d, u, l)
if C[i, j] = d then b[i, j] <- '↖'
else if C[i, j] = u then b[i, j] <- '↑'
else b[i, j] <- '←'
return (C[m, n], b)
PRINT_ALIGN(X, Y, b, i, j) { prints the alignment columns left to right }
if i = 0 and j = 0 then return
if b[i, j] = '↖' then
PRINT_ALIGN(X, Y, b, i-1, j-1); print column (x_i over y_j)
else if b[i, j] = '↑' then
PRINT_ALIGN(X, Y, b, i-1, j); print column (x_i over '-')
else
PRINT_ALIGN(X, Y, b, i, j-1); print column ('-' over y_j)The cost is (comparisons and additions between integers); reconstruction takes calls.
Worked example
, , , for , . Bold marks the reconstruction path.
| A | G | C | T | ||
|---|---|---|---|---|---|
| 0 | −2← | −4← | −6← | −8← | |
| A | −2↑ | 1↖ | −1← | −3← | −5← |
| C | −4↑ | −1↑ | −2↖ | 0↖ | −2← |
| C | −6↑ | −3↑ | −4↖ | −1↖ | −3↖ |
| G | −8↑ | −5↑ | −2↖ | −3↑ | −4↖ |
| T | −10↑ | −7↑ | −4↑ | −5↖ | −2↖ |
Cells by hand:
- : , so ; the other two choices give . Maximum , .
- : : ; ; . Maximum , .
- : : , against and .
- : , : ; ; . Maximum with : is aligned with a space.
Result: . Reconstruction: column ; column ; column ; column ; column . Read forwards:
Z^X = A C C G T
Z^Y = A G C - T cost: 1 + (-3) + 1 + (-2) + 1 = -2Linear space
DNA strings are very long and space is unacceptable. If only the optimal cost is needed, a single vector suffices, assuming (otherwise swap the strings). At the start of iteration inside iteration , holds the already computed row and holds row . Computing needs , and . The first must be saved before overwriting : it is kept in the variable prev.
ALIGNMENT_COST(X, Y, S, g) { constraint: |X| >= |Y| }
m <- |X|; n <- |Y|
for j <- 0 to n do C[j] <- j * g { row 0 }
for i <- 1 to m do
prev <- C[0] { C(i-1, 0), needed for column j = 1 }
C[0] <- i * g { C(i, 0) }
for j <- 1 to n do
new <- max(prev + S[x_i, y_j], C[j] + g, C[j-1] + g)
prev <- C[j] { C(i-1, j), for column j+1 }
C[j] <- new
return C[n]In the example, after iteration the vector is , after it is , and at the end . Time , auxiliary space .
Memoization and space. Memoized code cannot save space, because subinstances are generated in dynamic, unordered fashion. In exchange, on very similar sequences it does much less work than bottom-up. Trade-off: with quadratic space available, memoization is preferable; with linear space, bottom-up is needed.
Longest palindromic subsequence (LPS)
Definition. A string is a palindrome if for , i.e. it equals its reverse. The empty string is a palindrome. There are even-length () and odd-length () palindromes.
Given , find , its longest palindromic subsequence. For example has .
The subproblem space
If is a palindromic subsequence of realized by indices , then is also a palindrome and a subsequence of . A character is removed from each end, so we need substrings , not prefixes: the space is , of cardinality .
Optimal substructure
Let be an LPS of .
- : (base).
- : if then , otherwise or (base).
- :
- if , then and is an LPS of ;
- if , then is the longer of an LPS of and an LPS of .
Proof of 3, . First . If or , then would still be a palindrome and a subsequence of (neither nor is among the indices of ), characters longer: contradiction. So and is a palindromic subsequence of . If it were not an LPS, take an LPS of : would be a longer palindromic subsequence of (cut-and-paste).
Proof of 3, . cannot equal both and . If , index is unused and is a subsequence of ; if , is a subsequence of . In each case, by cut-and-paste, is an LPS of that substring. Since the LPS of and of are also palindromic subsequences of , is the longer of the two.
Recurrence and additional information
With , for :
Additional information for : if the LPS is ; if it equals ; if it equals .
Bottom-up code by diagonals
Let be the substring length. Base cases lie on diagonals and . For cell depends on (length ) and on , (length ): a scan by increasing diagonals is consistent. Scanning by rows from down to , or by columns from to (rows decreasing), also works.
COMPUTE_P(X)
n <- |X|
for i <- 1 to n-1 do
P[i, i] <- 1
if x_i = x_{i+1} then P[i, i+1] <- 2 else P[i, i+1] <- 1
P[n, n] <- 1
for l <- 3 to n do
for i <- 1 to n - l + 1 do
j <- i + l - 1
if x_i = x_j then
P[i, j] <- P[i+1, j-1] + 2; B[i, j] <- '↙'
else if P[i+1, j] >= P[i, j-1] then
P[i, j] <- P[i+1, j]; B[i, j] <- '↓'
else
P[i, j] <- P[i, j-1]; B[i, j] <- '←'
return (P[1, n], B)Cost. Space for and . One character comparison for every substring of length , i.e. every pair :
If only the length matters, three vectors (diagonals , , ) give linear space.
Worked example
(). Each cell with shows and the arrow; bold marks cells visited by the reconstruction.
| 1: A | 2: B | 3: C | 4: B | 5: D | 6: A | 7: C | 8: B | |
|---|---|---|---|---|---|---|---|---|
| 1: A | 1 | 1 | 1↓ | 3↓ | 3↓ | 5↙ | 5← | 5↓ |
| 2: B | 1 | 1 | 3↙ | 3← | 3← | 3↓ | 5↙ | |
| 3: C | 1 | 1 | 1↓ | 1↓ | 3↙ | 3↓ | ||
| 4: B | 1 | 1 | 1↓ | 1↓ | 3↙ | |||
| 5: D | 1 | 1 | 1↓ | 1↓ | ||||
| 6: A | 1 | 1 | 1↓ | |||||
| 7: C | 1 | 1 | ||||||
| 8: B | 1 |
Some cells: : , so (). : , , tie, chooses . : , . : , , so .
Reconstruction: goes to , which is and prints ; is and prints ; is and goes to , where and : print ; going back up prints and . The LPS is , of length .
PRINT_LPS(X, B, i, j) { first call: PRINT_LPS(X, B, 1, n) }
if i = j then print(x_i); return
if j = i + 1 then
if x_i = x_j then print(x_i x_j) else print(x_i)
return
if B[i, j] = '↙' then
print(x_i)
PRINT_LPS(X, B, i+1, j-1)
print(x_j)
else if B[i, j] = '↓' then PRINT_LPS(X, B, i+1, j)
else PRINT_LPS(X, B, i, j-1)The returns in the base cases are indispensable. The call tree has one node per level and drops by or per level, so comparisons are .
Relation with the LCS. has the same length as , with the reversed string. The dedicated code is cheaper: it uses only the upper triangle ( comparisons instead of ).
def lps_len(x):
n = len(x)
p = [[0] * n for _ in range(n)]
for i in range(n):
p[i][i] = 1
for i in range(n - 1):
p[i][i + 1] = 2 if x[i] == x[i + 1] else 1
for l in range(3, n + 1):
for i in range(n - l + 1):
j = i + l - 1
p[i][j] = p[i + 1][j - 1] + 2 if x[i] == x[j] else max(p[i + 1][j], p[i][j - 1])
return p[0][n - 1]
assert lps_len("ABCBDACB") == 5 and lps_len("SOBS") == 3Typical exam questions
- What is and how many comparisons does
COMPUTE_Pdo for ? Answer: ; . - Why substrings rather than prefixes for the LPS, and how is the table scanned? Answer: characters are removed from both ends, so substrings are needed; depends on cells of length and , hence by increasing diagonals.
- With , , , for , find . Answer: , , ; with : alignment .
Versione ripasso
- Alignment. Alphabet . Pair of length : subsequence of , of , spaces only outside the symbols of and , never two spaces in one position. Position weight: if no space, otherwise; cost = sum; maximize. Example , , , , : costs (optimal); costs .
- Substructure (prefixes , last position of three types, cut-and-paste): from , from , from . Base: the only alignment of has spaces, cost .
- Recurrence: , , . Arrows ; time , reconstruction .
- One vector (cost only, ):
prev <- C[0]; C[0] <- i*g; for j: new <- max(prev + S[x_i,y_j], C[j] + g, C[j-1] + g); prev <- C[j]; C[j] <- new. Space . Memoized: no space saving, less work on similar sequences.
| A | G | C | T | ||
|---|---|---|---|---|---|
| 0 | −2← | −4← | −6← | −8← | |
| A | −2↑ | 1↖ | −1← | −3← | −5← |
| C | −4↑ | −1↑ | −2↖ | 0↖ | −2← |
| C | −6↑ | −3↑ | −4↖ | −1↖ | −3↖ |
| G | −8↑ | −5↑ | −2↖ | −3↑ | −4↖ |
| T | −10↑ | −7↑ | −4↑ | −5↖ | −2↖ |
, : , alignment (cost ). Cells: : ; : ; : with .
ALIGN: C[i,0] <- i*g; C[0,j] <- j*g; for i, j >= 1: d <- C[i-1,j-1] + S[x_i,y_j]; u <- C[i-1,j] + g; l <- C[i,j-1] + g
C[i,j] <- max(d,u,l); b[i,j] <- '↖' if = d, '↑' if = u, else '←'- LPS. Palindrome: , also . Space: substrings (), because both ends are removed. For : gives and an LPS of ; : the longer of LPS and LPS.
- Recurrence: ; if , else ; for : if , else . Arrows . Scan by diagonals (rows from to or columns also work). Comparisons: ; printing .
COMPUTE_P(X): P[i,i] <- 1; P[i,i+1] <- 2 if x_i = x_{i+1} else 1
for l <- 3 to n do for i <- 1 to n-l+1 do
j <- i+l-1
if x_i = x_j then P[i,j] <- P[i+1,j-1] + 2; B[i,j] <- '↙'
else if P[i+1,j] >= P[i,j-1] then P[i,j] <- P[i+1,j]; B[i,j] <- '↓'
else P[i,j] <- P[i,j-1]; B[i,j] <- '←'- Example: (), . Reconstruction: , prints , prints , , base prints ; then , : LPS . Cells: , . has the length of , but the dedicated code uses half the cells.
- Proof for : if (or ), would be a longer palindrome; if were not an LPS of , replace it with one (cut-and-paste). For : cannot equal both, so lives in or .
- Printing:
PRINT_LPS(X,B,i,j): prints and stops; prints if equal, else , and stops; : print , recurse on , print ; : recurse on ; : on . One node per level: comparisons. - Typical mistakes: prefixes instead of substrings for the LPS; scanning by increasing rows; adding instead of when ; overwriting before saving
prev; printing base cases withoutreturn.