1if a[i-1] == b[j-1]:2 L[i][j] = L[i-1][j-1] + 13else:4 L[i][j] = max(L[i-1][j],5 L[i][j-1])1if a[i-1] == b[j-1]:2 D[i][j] = D[i-1][j-1]3else:4 D[i][j] = 1 + min(5 D[i-1][j-1], # replace6 D[i-1][j], # delete7 D[i][j-1]) # insertHORSEROS
Cells: one per pair of prefixes, row 0 and column 0 are the empty wordTiles: the letters of HORSE (rows) and ROS (columns)Yellow frame: the cell being worked out; dashed: the neighbours it comparesOne table compares HORSE with ROS: cell [i][j] answers the question for the first i letters of each word. Each cell is worked out from the diagonal, the cell above and the cell to the left, all filled earlier; the chip shows which one the rule picked. The LCS rule ends with 2 (OS), the edit-distance rule with 3 (HORSE → RORSE → ROSE → ROS).

Longest common subsequence

  1. A subsequence keeps some letters of a word in their order and may skip others. HORSE and ROS share the subsequence OS (and RS). The longest common subsequence, LCS, is the longest one two words share.

Edit distance

Cost

What happens

;; step 1/11 · subsequence
a = "HORSE", b = "ROS"
common subsequences: "O", "R", "S", "OS", "RS"
none of length 3, so LCS length = 2

substring = letters next to each other
subsequence = same order, gaps allowed

This lesson works on prefixes (the first i letters), as CLRS §14.4 does. MIT 6.006 uses suffixes (from letter i to the end) and fills the table from the bottom-right instead. The rule and the answer are the same, mirrored. When two neighbours tie, the walk back here prefers the diagonal, then up, then left (CLRS records ↑ when up ≥ left, too). Another tie rule can give a different subsequence or edit script of the same length: RS is also a longest common subsequence of HORSE and ROS.