Dynamic programmingAnimated
Longest Common Subsequence (LCS)
A table of the longest common subsequence of every pair of prefixes.
Time
O(n · m)
Extra space
O(n · m)
Use it for
diff tools, DNA comparison.
How it works
- A subsequence keeps the order of letters but may skip some.
- Cell (i, j) = length of the LCS of the first i letters of A and the first j letters of B.
- If the letters match, extend the diagonal: cell = diagonal + 1. Otherwise take the larger of the cell above and the cell to the left.
- Read the answer from the bottom-right, then trace back to recover the actual letters. O(m × n).
Watch it run
Loading animation…