Salta al contenuto
Note per Studenti String Alignment and Longest Palindromic Subsequence Report

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 ΣDNA={A,C,G,T}\Sigma_{DNA} = \{A, C, G, T\}; for alignment it is extended with a space character, ΣDNAE={A,C,G,T,−}\Sigma^E_{DNA} = \{A, C, G, T, -\}. The optimal cost is a similarity metric between the two strings.

Problem definition

Definition (alignment). Given X=⟨x1,…,xm⟩X = \langle x_1, \dots, x_m \rangle and Y=⟨y1,…,yn⟩Y = \langle y_1, \dots, y_n \rangle over ΣDNA\Sigma_{DNA}, an alignment of length kk is a pair of strings ZX=⟨z1X,…,zkX⟩Z^X = \langle z^X_1, \dots, z^X_k \rangle, ZY=⟨z1Y,…,zkY⟩Z^Y = \langle z^Y_1, \dots, z^Y_k \rangle over ΣDNAE\Sigma^E_{DNA}, with k≥max⁡{m,n}k \ge \max\{m, n\}, such that:

  1. XX is a subsequence of ZXZ^X and YY is a subsequence of ZYZ^Y;
  2. positions that do not realize symbols of XX (resp. YY) contain only −-;
  3. no position has two spaces: (zrX∈ΣDNA)∨(zrY∈ΣDNA)(z^X_r \in \Sigma_{DNA}) \lor (z^Y_r \in \Sigma_{DNA}).

Each column of the alignment is of one of three types: symbol of XX over symbol of YY; symbol of XX over a space; space over symbol of YY.

Example. X=⟨A,G,T,T⟩X = \langle A, G, T, T \rangle, Y=⟨A,T,T⟩Y = \langle A, T, T \rangle. 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 S∈Z4×4S \in \mathbb{Z}^{4 \times 4} gives an integer sUVs_{UV} for each ordered pair of nucleotides (usually symmetric, positive on the diagonal for matches, negative elsewhere); the gap penalty g∈Zg \in \mathbb{Z} (usually negative) is the weight of a position with a space. The weight of a position and the cost of the alignment are

p(zrX,zrY)={szrXzrYzrX≠− ∧ zrY≠−gotherwisec(ZX,ZY)=∑r=1kp(zrX,zrY).p(z^X_r, z^Y_r) = \begin{cases} s_{z^X_r z^Y_r} & z^X_r \ne - \ \land \ z^Y_r \ne - \\ g & \text{otherwise} \end{cases} \qquad c(Z^X, Z^Y) = \sum_{r=1}^{k} p(z^X_r, z^Y_r).

Optimal alignment problem. Given X,Y∈ΣDNA∗X, Y \in \Sigma_{DNA}^*, SS and gg, find the maximum cost of an alignment of the two strings.

Example (continued). sUU=1s_{UU} = 1, sUV=−3s_{UV} = -3 for U≠VU \ne V, g=−2g = -2. The first alignment costs 1+(−2)+1+1=11 + (-2) + 1 + 1 = 1; the second 1+(−3)+1+(−2)=−31 + (-3) + 1 + (-2) = -3. 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, {(Xi,Yj):0≤i≤m, 0≤j≤n}\{(X_i, Y_j) : 0 \le i \le m,\ 0 \le j \le n\}.

Base cases. If i=0i = 0, the only feasible alignment of (ε,Yj)(\varepsilon, Y_j) is jj spaces over YjY_j (condition 3 forbids two spaces in a position), of cost j⋅gj \cdot g. Symmetrically for j=0j = 0 the cost is i⋅gi \cdot g; for i=j=0i = j = 0 it is 00.

Non-base cases (i>0i > 0, j>0j > 0). Let (ZXi,ZYj)(Z^{X_i}, Z^{Y_j}) be an optimal alignment of (Xi,Yj)(X_i, Y_j), of length kk. The last position has only three possible types:

  1. zkXi=xiz^{X_i}_k = x_i and zkYj=yjz^{Y_j}_k = y_j. Then the first k−1k - 1 positions are an optimal alignment of (Xi−1,Yj−1)(X_{i-1}, Y_{j-1}) (otherwise cut-and-paste would give a better one) and c=c(ZXi−1,ZYj−1)+sxiyjc = c(Z^{X_{i-1}}, Z^{Y_{j-1}}) + s_{x_i y_j}.
  2. zkXi=xiz^{X_i}_k = x_i and zkYj=−z^{Y_j}_k = -. The first k−1k - 1 positions are an optimal alignment of (Xi−1,Yj)(X_{i-1}, Y_j) and c=c(ZXi−1,ZYj)+gc = c(Z^{X_{i-1}}, Z^{Y_j}) + g.
  3. zkXi=−z^{X_i}_k = - and zkYj=yjz^{Y_j}_k = y_j: symmetric, an optimal alignment of (Xi,Yj−1)(X_i, Y_{j-1}) and c=c(ZXi,ZYj−1)+gc = c(Z^{X_i}, Z^{Y_{j-1}}) + g.

The three alignments built from optima of the subproblems are all feasible, so the one of maximum cost wins.

Cost recurrence

With C(i,j)C(i, j) the cost of the optimal alignment of (Xi,Yj)(X_i, Y_j):

C(i,j)={j⋅gi=0i⋅gj=0max⁡{ C(i−1,j−1)+sxiyj,  C(i−1,j)+g,  C(i,j−1)+g }i>0 ∧ j>0C(i, j) = \begin{cases} j \cdot g & i = 0 \\ i \cdot g & j = 0 \\ \max\{\, C(i-1, j-1) + s_{x_i y_j},\ \ C(i-1, j) + g,\ \ C(i, j-1) + g \,\} & i > 0 \ \land \ j > 0 \end{cases}

To rebuild the alignment, store an arrow as in the LCS: ↖\nwarrow, ↑\uparrow or ←\leftarrow 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 Θ(mn)\Theta(mn) (comparisons and additions between integers); reconstruction takes O(m+n)O(m + n) calls.

Worked example

X=ACCGTX = ACCGT, Y=AGCTY = AGCT, sUU=1s_{UU} = 1, sUV=−3s_{UV} = -3 for U≠VU \ne V, g=−2g = -2. Bold marks the reconstruction path.

ε\varepsilon A G C T
ε\varepsilon 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:

  • (1,1)(1, 1): x1=y1=Ax_1 = y_1 = A, so C(0,0)+sAA=1C(0, 0) + s_{AA} = 1; the other two choices give −4-4. Maximum 11, ↖\nwarrow.
  • (2,2)(2, 2): x2=C≠G=y2x_2 = C \ne G = y_2: C(1,1)+sCG=1−3=−2C(1,1) + s_{CG} = 1 - 3 = -2; C(1,2)+g=−3C(1,2) + g = -3; C(2,1)+g=−3C(2,1) + g = -3. Maximum −2-2, ↖\nwarrow.
  • (2,3)(2, 3): x2=y3=Cx_2 = y_3 = C: C(1,2)+1=0C(1,2) + 1 = 0, against −5-5 and −4-4.
  • (4,3)(4, 3): x4=Gx_4 = G, y3=Cy_3 = C: C(3,2)+sGC=−7C(3,2) + s_{GC} = -7; C(3,3)+g=−3C(3,3) + g = -3; C(4,2)+g=−4C(4,2) + g = -4. Maximum −3-3 with ↑\uparrow: GG is aligned with a space.

Result: C(5,4)=−2C(5, 4) = -2. Reconstruction: (5,4) ↖(5,4)\ \nwarrow column (T,T)(T, T); (4,3) ↑(4,3)\ \uparrow column (G,−)(G, -); (3,3) ↖(3,3)\ \nwarrow column (C,C)(C, C); (2,2) ↖(2,2)\ \nwarrow column (C,G)(C, G); (1,1) ↖(1,1)\ \nwarrow column (A,A)(A, A). Read forwards:

Z^X = A C C G T
Z^Y = A G C - T       cost: 1 + (-3) + 1 + (-2) + 1 = -2

Linear space

DNA strings are very long and Θ(mn)\Theta(mn) space is unacceptable. If only the optimal cost is needed, a single vector C[0..n]C[0..n] suffices, assuming n≤mn \le m (otherwise swap the strings). At the start of iteration jj inside iteration ii, C[0..j−1]C[0..j-1] holds the already computed row ii and C[j..n]C[j..n] holds row i−1i - 1. Computing C(i,j)C(i, j) needs C(i−1,j−1)C(i-1, j-1), C(i−1,j)=C[j]C(i-1, j) = C[j] and C(i,j−1)=C[j−1]C(i, j-1) = C[j-1]. The first must be saved before overwriting C[j]C[j]: 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 i=1i = 1 the vector is (−2,1,−1,−3,−5)(-2, 1, -1, -3, -5), after i=3i = 3 it is (−6,−3,−4,−1,−3)(-6, -3, -4, -1, -3), and at the end C[4]=−2C[4] = -2. Time Θ(mn)\Theta(mn), auxiliary space Θ(min⁡{m,n})\Theta(\min\{m, n\}).

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 Z=⟨z1,…,zm⟩Z = \langle z_1, \dots, z_m \rangle is a palindrome if z1+h=zm−hz_{1+h} = z_{m-h} for 0≤h≤m−10 \le h \le m - 1, i.e. it equals its reverse. The empty string is a palindrome. There are even-length (⟨A,C,C,A⟩\langle A, C, C, A \rangle) and odd-length (⟨A,I,A⟩\langle A, I, A \rangle) palindromes.

Given X=⟨x1,…,xn⟩X = \langle x_1, \dots, x_n \rangle, find LPS(X)\text{LPS}(X), its longest palindromic subsequence. For example X=⟨S,O,B,S⟩X = \langle S, O, B, S \rangle has LPS(X)=⟨S,O,S⟩\text{LPS}(X) = \langle S, O, S \rangle.

The subproblem space

If Z=⟨z1,…,zm⟩Z = \langle z_1, \dots, z_m \rangle is a palindromic subsequence of XX realized by indices j1<⋯<jmj_1 < \dots < j_m, then Z2..m−1Z_{2..m-1} is also a palindrome and a subsequence of X2..n−1X_{2..n-1}. A character is removed from each end, so we need substrings Xi..jX_{i..j}, not prefixes: the space is {Xi..j:1≤i≤j≤n}\{X_{i..j} : 1 \le i \le j \le n\}, of cardinality Θ(n2)\Theta(n^2).

Optimal substructure

Let Z=⟨z1,…,zm⟩Z = \langle z_1, \dots, z_m \rangle be an LPS of Xi..jX_{i..j}.

  1. i=ji = j: Z=⟨xi⟩Z = \langle x_i \rangle (base).
  2. j=i+1j = i + 1: if xi=xjx_i = x_j then Z=⟨xi,xj⟩Z = \langle x_i, x_j \rangle, otherwise Z=⟨xi⟩Z = \langle x_i \rangle or ⟨xj⟩\langle x_j \rangle (base).
  3. j>i+1j > i + 1:
    • if xi=xjx_i = x_j, then z1=zm=xiz_1 = z_m = x_i and Z2..m−1Z_{2..m-1} is an LPS of Xi+1..j−1X_{i+1..j-1};
    • if xi≠xjx_i \ne x_j, then ZZ is the longer of an LPS of Xi+1..jX_{i+1..j} and an LPS of Xi..j−1X_{i..j-1}.

Proof of 3, xi=xjx_i = x_j. First z1=zm=xiz_1 = z_m = x_i. If Z=εZ = \varepsilon or z1=zm≠xiz_1 = z_m \ne x_i, then ⟨xi,Z,xj⟩\langle x_i, Z, x_j \rangle would still be a palindrome and a subsequence of Xi..jX_{i..j} (neither ii nor jj is among the indices of ZZ), 22 characters longer: contradiction. So m≥2m \ge 2 and Z2..m−1Z_{2..m-1} is a palindromic subsequence of Xi+1..j−1X_{i+1..j-1}. If it were not an LPS, take an LPS Z′Z' of Xi+1..j−1X_{i+1..j-1}: ⟨xi,Z′,xj⟩\langle x_i, Z', x_j \rangle would be a longer palindromic subsequence of Xi..jX_{i..j} (cut-and-paste).

Proof of 3, xi≠xjx_i \ne x_j. z1=zmz_1 = z_m cannot equal both xix_i and xjx_j. If z1=zm≠xiz_1 = z_m \ne x_i, index ii is unused and ZZ is a subsequence of Xi+1..jX_{i+1..j}; if z1=zm≠xjz_1 = z_m \ne x_j, ZZ is a subsequence of Xi..j−1X_{i..j-1}. In each case, by cut-and-paste, ZZ is an LPS of that substring. Since the LPS of Xi+1..jX_{i+1..j} and of Xi..j−1X_{i..j-1} are also palindromic subsequences of Xi..jX_{i..j}, ZZ is the longer of the two. □\square

Recurrence and additional information

With p(i,j)=∣LPS(Xi..j)∣p(i, j) = |\text{LPS}(X_{i..j})|, for 1≤i≤j≤n1 \le i \le j \le n:

p(i,j)={1i=j2j=i+1 ∧ xi=xj1j=i+1 ∧ xi≠xj2+p(i+1,j−1)j>i+1 ∧ xi=xjmax⁡{p(i+1,j), p(i,j−1)}j>i+1 ∧ xi≠xjp(i, j) = \begin{cases} 1 & i = j \\ 2 & j = i + 1 \ \land \ x_i = x_j \\ 1 & j = i + 1 \ \land \ x_i \ne x_j \\ 2 + p(i+1, j-1) & j > i + 1 \ \land \ x_i = x_j \\ \max\{p(i+1, j),\ p(i, j-1)\} & j > i + 1 \ \land \ x_i \ne x_j \end{cases}

Additional information for j>i+1j > i + 1: b(i,j)=↙b(i, j) = \swarrow if the LPS is ⟨xi,LPS(Xi+1..j−1),xj⟩\langle x_i, \text{LPS}(X_{i+1..j-1}), x_j \rangle; ↓\downarrow if it equals LPS(Xi+1..j)\text{LPS}(X_{i+1..j}); ←\leftarrow if it equals LPS(Xi..j−1)\text{LPS}(X_{i..j-1}).

Bottom-up code by diagonals

Let ℓ=j−i+1\ell = j - i + 1 be the substring length. Base cases lie on diagonals ℓ=1\ell = 1 and ℓ=2\ell = 2. For ℓ≥3\ell \ge 3 cell (i,j)(i, j) depends on (i+1,j−1)(i+1, j-1) (length ℓ−2\ell - 2) and on (i+1,j)(i+1, j), (i,j−1)(i, j-1) (length ℓ−1\ell - 1): a scan by increasing diagonals is consistent. Scanning by rows from nn down to 11, or by columns from 11 to nn (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 Θ(n2)\Theta(n^2) for PP and BB. One character comparison for every substring of length ≥2\ge 2, i.e. every pair i<ji < j:

T(n)=∑i=1n−1∑j=i+1n1=∑i′=1n−1i′=n(n−1)2=Θ(n2).T(n) = \sum_{i=1}^{n-1} \sum_{j=i+1}^{n} 1 = \sum_{i'=1}^{n-1} i' = \frac{n(n-1)}{2} = \Theta(n^2).

If only the length matters, three vectors (diagonals ℓ\ell, ℓ−1\ell - 1, ℓ−2\ell - 2) give linear space.

Worked example

X=ABCBDACBX = ABCBDACB (n=8n = 8). Each cell (i,j)(i, j) with i<ji < j shows p(i,j)p(i, j) 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: (2,4)(2, 4): x2=x4=Bx_2 = x_4 = B, so p=2+p(3,3)=3p = 2 + p(3, 3) = 3 (↙\swarrow). (1,3)(1, 3): A≠CA \ne C, p(2,3)=p(1,2)=1p(2,3) = p(1,2) = 1, tie, ≥\ge chooses ↓\downarrow. (1,6)(1, 6): x1=x6=Ax_1 = x_6 = A, p=2+p(2,5)=5p = 2 + p(2, 5) = 5. (1,8)(1, 8): A≠BA \ne B, p(2,8)=5≥p(1,7)=5p(2,8) = 5 \ge p(1,7) = 5, so ↓\downarrow.

Reconstruction: (1,8) ↓(1,8)\ \downarrow goes to (2,8)(2,8), which is ↙\swarrow and prints x2=Bx_2 = B; (3,7)(3,7) is ↙\swarrow and prints CC; (4,6)(4,6) is ↓\downarrow and goes to (5,6)(5,6), where j=i+1j = i + 1 and x5=D≠A=x6x_5 = D \ne A = x_6: print x5=Dx_5 = D; going back up prints x7=Cx_7 = C and x8=Bx_8 = B. The LPS is ⟨B,C,D,C,B⟩\langle B, C, D, C, B \rangle, of length p(1,8)=5p(1, 8) = 5.

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 j−ij - i drops by 11 or 22 per level, so comparisons are Θ(n)\Theta(n).

Relation with the LCS. LPS(X)\text{LPS}(X) has the same length as LCS(X,XR)\text{LCS}(X, X^R), with XRX^R the reversed string. The dedicated code is cheaper: it uses only the upper triangle (n(n−1)/2n(n-1)/2 comparisons instead of n2n^2).

python
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") == 3

Typical exam questions

  1. What is LPS(⟨S,O,B,S⟩)\text{LPS}(\langle S, O, B, S \rangle) and how many comparisons does COMPUTE_P do for n=10n = 10? Answer: ⟨S,O,S⟩\langle S, O, S \rangle; n(n−1)/2=45n(n-1)/2 = 45.
  2. Why substrings rather than prefixes for the LPS, and how is the table scanned? Answer: characters are removed from both ends, so substrings Xi..jX_{i..j} are needed; (i,j)(i, j) depends on cells of length ℓ−2\ell - 2 and ℓ−1\ell - 1, hence by increasing diagonals.
  3. With sUU=1s_{UU} = 1, sUV=−3s_{UV} = -3, g=−2g = -2, for X=⟨A,C⟩X = \langle A, C \rangle, Y=⟨A⟩Y = \langle A \rangle find C(2,1)C(2, 1). Answer: C(1,1)=1C(1,1) = 1, C(2,0)=−4C(2,0) = -4, C(1,0)=−2C(1,0) = -2; C(2,1)=max⁡{−2−3, 1−2, −4−2}=−1C(2,1) = \max\{-2 - 3,\ 1 - 2,\ -4 - 2\} = -1 with ↑\uparrow: alignment AC/A−AC / A-.

Versione ripasso

  • Alignment. Alphabet {A,C,G,T,−}\{A, C, G, T, -\}. Pair (ZX,ZY)(Z^X, Z^Y) of length k≥max⁡{m,n}k \ge \max\{m, n\}: XX subsequence of ZXZ^X, YY of ZYZ^Y, spaces only outside the symbols of XX and YY, never two spaces in one position. Position weight: szrXzrYs_{z^X_r z^Y_r} if no space, gg otherwise; cost = sum; maximize. Example X=AGTTX = AGTT, Y=ATTY = ATT, sUU=1s_{UU} = 1, sUV=−3s_{UV} = -3, g=−2g = -2: AGTT/A−TTAGTT / A-TT costs 1−2+1+1=11 - 2 + 1 + 1 = 1 (optimal); AGTT/ATT−AGTT / ATT- costs −3-3.
  • Substructure (prefixes Xi,YjX_i, Y_j, last position of three types, cut-and-paste): (xi,yj)(x_i, y_j) from (Xi−1,Yj−1)(X_{i-1}, Y_{j-1}), (xi,−)(x_i, -) from (Xi−1,Yj)(X_{i-1}, Y_j), (−,yj)(-, y_j) from (Xi,Yj−1)(X_i, Y_{j-1}). Base: the only alignment of (ε,Yj)(\varepsilon, Y_j) has jj spaces, cost jgjg.
  • Recurrence: C(i,0)=igC(i,0) = ig, C(0,j)=jgC(0,j) = jg, C(i,j)=max⁡{C(i−1,j−1)+sxiyj, C(i−1,j)+g, C(i,j−1)+g}C(i,j) = \max\{C(i-1,j-1) + s_{x_i y_j},\ C(i-1,j) + g,\ C(i,j-1) + g\}. Arrows ↖,↑,←\nwarrow, \uparrow, \leftarrow; time Θ(mn)\Theta(mn), reconstruction O(m+n)O(m + n).
  • One vector (cost only, ∣X∣≥∣Y∣|X| \ge |Y|): 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 Θ(min⁡{m,n})\Theta(\min\{m,n\}). Memoized: no space saving, less work on similar sequences.
ε\varepsilon A G C T
ε\varepsilon 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↖

X=ACCGTX = ACCGT, Y=AGCTY = AGCT: C(5,4)=−2C(5,4) = -2, alignment ACCGT/AGC−TACCGT / AGC-T (cost 1−3+1−2+11 - 3 + 1 - 2 + 1). Cells: (2,2)(2,2): max⁡{1−3, −1−2, −1−2}=−2\max\{1 - 3,\ -1 - 2,\ -1 - 2\} = -2; (2,3)(2,3): max⁡{−1+1, −3−2, −2−2}=0\max\{-1 + 1,\ -3 - 2,\ -2 - 2\} = 0; (4,3)(4,3): max⁡{−4−3, −1−2, −2−2}=−3\max\{-4 - 3,\ -1 - 2,\ -2 - 2\} = -3 with ↑\uparrow.

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: z1+h=zm−hz_{1+h} = z_{m-h}, also ε\varepsilon. Space: substrings Xi..jX_{i..j} (Θ(n2)\Theta(n^2)), because both ends are removed. For j>i+1j > i + 1: xi=xjx_i = x_j gives z1=zm=xiz_1 = z_m = x_i and Z2..m−1Z_{2..m-1} an LPS of Xi+1..j−1X_{i+1..j-1}; xi≠xjx_i \ne x_j: the longer of LPS(Xi+1..j)(X_{i+1..j}) and LPS(Xi..j−1)(X_{i..j-1}).
  • Recurrence: p(i,i)=1p(i,i) = 1; p(i,i+1)=2p(i,i+1) = 2 if xi=xi+1x_i = x_{i+1}, else 11; for j>i+1j > i+1: 2+p(i+1,j−1)2 + p(i+1,j-1) if xi=xjx_i = x_j, else max⁡{p(i+1,j),p(i,j−1)}\max\{p(i+1,j), p(i,j-1)\}. Arrows ↙,↓,←\swarrow, \downarrow, \leftarrow. Scan by diagonals ℓ=3..n\ell = 3..n (rows from nn to 11 or columns also work). Comparisons: ∑i=1n−1(n−i)=n(n−1)2\sum_{i=1}^{n-1}(n-i) = \frac{n(n-1)}{2}; printing Θ(n)\Theta(n).
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: X=ABCBDACBX = ABCBDACB (n=8n = 8), p(1,8)=5p(1,8) = 5. Reconstruction: (1,8) ↓(1,8)\,\downarrow, (2,8) ↙(2,8)\,\swarrow prints BB, (3,7) ↙(3,7)\,\swarrow prints CC, (4,6) ↓(4,6)\,\downarrow, (5,6)(5,6) base prints DD; then CC, BB: LPS =BCDCB= BCDCB. Cells: p(1,6)=2+p(2,5)=5p(1,6) = 2 + p(2,5) = 5, p(2,4)=2+p(3,3)=3p(2,4) = 2 + p(3,3) = 3. LPS(X)\text{LPS}(X) has the length of LCS(X,XR)\text{LCS}(X, X^R), but the dedicated code uses half the cells.
  • Proof for xi=xjx_i = x_j: if z1=zm≠xiz_1 = z_m \ne x_i (or Z=εZ = \varepsilon), ⟨xi,Z,xj⟩\langle x_i, Z, x_j \rangle would be a longer palindrome; if Z2..m−1Z_{2..m-1} were not an LPS of Xi+1..j−1X_{i+1..j-1}, replace it with one (cut-and-paste). For xi≠xjx_i \ne x_j: z1=zmz_1 = z_m cannot equal both, so ZZ lives in Xi+1..jX_{i+1..j} or Xi..j−1X_{i..j-1}.
  • Printing: PRINT_LPS(X,B,i,j): i=ji = j prints xix_i and stops; j=i+1j = i+1 prints xixjx_ix_j if equal, else xix_i, and stops; ↙\swarrow: print xix_i, recurse on (i+1,j−1)(i+1,j-1), print xjx_j; ↓\downarrow: recurse on (i+1,j)(i+1,j); ←\leftarrow: on (i,j−1)(i,j-1). One node per level: Θ(n)\Theta(n) comparisons.
  • Typical mistakes: prefixes instead of substrings for the LPS; scanning by increasing rows; adding 11 instead of 22 when xi=xjx_i = x_j; overwriting C[j]C[j] before saving prev; printing base cases without return.

Teoria collegata