Longest Common Subsequence
Dynamic ProgrammingavgO(m·n)worstO(m·n)spaceO(m·n)
ε
G
X
T
X
A
Y
B
ε
A
G
G
T
A
B
Cell [i][j] will hold the LCS length of the first i letters of "AGGTAB" and the first j letters of "GXTXAYB"
1 / 55
How it works
Finds the longest sequence of letters that appears in both strings in the same order, not necessarily side by side. Cell [i][j] holds the answer for the first i letters of a and the first j letters of b: a matching pair extends the diagonal by one, otherwise the better of dropping a letter from either string wins. Walking back from the corner recovers the subsequence itself.
Complexity
- Best
- O(m·n)
- Average
- O(m·n)
- Worst
- O(m·n)
- Space
- O(m·n)