Longest Common Subsequence
Question (LC.77)
Given two strings, find the longest common subsequence (return length).
Example
I: "ABCD", "EDCA"
O: len("A") = 1
I: "ABCD", "EACB"
O: len("AB") = 2Analysis
The classic two sequence DP. Draw a grid then tabulation.
Approach
1. Define (optimal) subproblems
LCS(i,j) = longest common subsequence from A[:i] and B[:j]
2. Solve by prefix
if (A[i] == B[j])
LCS(i,j) = LCS(i-1,i-j) + 1
else
LCS(i,j) = Math.max(LCS(i,j-1), LCS(i-1,j))
3. Topo order
for i from 1 to n
for j from 1 to m
4. Init base
for i from 0 to n
LCS(i,0) = 0
for j from 0 to m
LCS(0,j) = 0
5. Final answer
LCS(n,m)Code
Time Complexity
#subproblems * time/subproblem = O(m*n) * O(1) = O(mn)
Last updated