Skip to content
StackDecode
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

  1. A subsequence keeps the order of letters but may skip some.
  2. Cell (i, j) = length of the LCS of the first i letters of A and the first j letters of B.
  3. If the letters match, extend the diagonal: cell = diagonal + 1. Otherwise take the larger of the cell above and the cell to the left.
  4. Read the answer from the bottom-right, then trace back to recover the actual letters. O(m × n).

Watch it run

Loading animation…