32. Longest Common Subsequence (Dynamic Programming)
32. Longest Common Subsequence (Dynamic Programming)
(Dynamic Programming)
2
Longest Common Subsequence
(LCS)
03/01/2025 3
Longest Common Subsequence
Input: X = < x 1 , x 2, …, x m>
Y = < y1 , y2 , …, y n >
03/01/2025 5
LCS Algorithm
• First we’ll find the length of LCS. Later we’ll modify
the algorithm to find LCS itself.
• Define Xi, Yj to be the prefixes of X and Y of length i
and j respectively
• Define c[i,j] to be the length of LCS of Xi and Yj
• Then the length of LCS of X and Y will be c[m,n]
c[i 1, j 1] 1 if x[i ] y[ j ],
c[i, j ]
max(c[i, j 1], c[i 1, j ]) otherwise
03/01/2025 6
LCS recursive solution
c[i 1, j 1] 1 if x[i ] y[ j ],
c[i, j ]
max(c[i, j 1], c[i 1, j ]) otherwise
• We start with i = j = 0 (empty substrings of x and y)
03/01/2025 7
LCS recursive solution
c[i 1, j 1] 1 if x[i ] y[ j ],
c[i, j ]
max(c[i, j 1], c[i 1, j ]) otherwise
• When we calculate c[i,j], we consider two cases:
• First case: x[i]=y[j]: one more symbol in strings X
and Y matches, so the length of LCS Xi and Yj equals
to the length of LCS of smaller strings X i-1 and Yi-1 ,
plus 1
03/01/2025 8
LCS recursive solution
c[i 1, j 1] 1 if x[i ] y[ j ],
c[i, j ]
max(c[i, j 1], c[i 1, j ]) otherwise
03/01/2025 9
LCS recursive solution
03/01/2025 10
A Recursive Formula
X = < x 1, x 2, …, xm >, Y = < y1 , y 2, …, yn >
0 xi 0 0 0 0 0 0 • If xi = yj
1 A 0 b[i, j] = “ ”
2 B 0 c[i-1,j-1] • Else, if
c[i-1,j]
i c[i - 1, j] ≥ c[i, j-1]
3 C 0 c[i,j-1]
0 b[i, j] = “ ”
0 else
m D
b[i, j] = “ ”
j
13
LCS-LENGTH(X, Y, m, n)
The length of the LCS if one of the sequences
1. for i ← 1 to m
is empty is zero
2. do c[i, 0] ← 0
3. for j ← 0 to n
4. do c[0, j] ← 0
5. for i ← 1 to m
6. do for j ← 1 to n
7. do if xi = yj
Case 1: xi = yj
8. then c[i, j] ← c[i - 1, j - 1] + 1
9. b[i, j ] ← “ ”
10. else if c[i - 1, j] ≥ c[i, j - 1]
11. then c[i, j] ← c[i - 1, j]
12. b[i, j] ← “↑” Case 2: xi yj
13. else c[i, j] ← c[i, j - 1]
14. b[i, j] ← “←”
15. return c and b
Running time: (mn)
14
Example 0 if i = 0 or
X = A, B, C, B, D, A, B j=0
Y = B, D, C, A, B, A c[i, j] = c[i-1, j-1] + 1 if xi = yj
0 1 2
max(c[i, 3
j-1], 4
c[i-1,5j]) if6 xi yj
If xi = yj yj B D C A B A
0 xi
b[i, j] = “ ” 0 0 0 0 0 0 0
1 A
Else if c[i - 0 0 0 0 1 1 1
2 B
1, j] ≥ c[i, j-1] 0 1 1 1 1 2 2
b[i, j] = “ ”3 C 0 1 1 2 2 2 2
else 4 B 0 1 1 2 2 3 3
b[i, j] = “ 5” D 0
1 2
2
2
3
3
6 A 0 1 2 2 3 3 4
7 B 0 1 2 2 3 4 4
15
PRINT-LCS(b, X, i, j)
1. if i = 0 or j = 0 Running time: (m + n)
2. then return
3. if b[i, j] = “ ”
4. then PRINT-LCS(b, X, i - 1, j - 1)
5. print xi
6. elseif b[i, j] = “↑”
7. then PRINT-LCS(b, X, i - 1, j)
8. else PRINT-LCS(b, X, i, j - 1)