Longest common subsequence
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.
Trying every subsequence takes exponential time. Instead, build a table. Cell [i][j] holds the LCS length of the first i letters of HORSE and the first j of ROS. Row 0 and column 0 mean an empty word, so they hold 0.
Fill row by row. At [2][2] both prefixes end in O. An LCS can end with that O, so take the best answer without either O, the diagonal [1][1] = 0, and add 1: [2][2] = 1.
At [2][3], O and S differ, so one of them is not in the LCS. Drop the last letter of a (look up) or of b (look left) and keep the bigger: max(0, 1) = 1.
Going row by row, left to right, the three cells a rule reads are always filled already. The last cell answers the whole question: the LCS of HORSE and ROS has length 2.
The table holds lengths, not letters. Walk back from the corner: on a match step diagonally and keep the letter; otherwise step to the neighbour the value came from. The kept letters, read backwards, spell OS.
Edit distance
Edit distance counts the fewest one-letter edits (insert, delete or replace) that turn one word into another. Cell [i][j]: edits from the first i letters of HORSE to the first j of ROS. Row 0 needs j inserts, column 0 needs i deletes.
Matching letters cost nothing: copy the diagonal. Otherwise pay 1 edit plus the cheapest neighbour: diagonal = replace, up = delete, left = insert. At [1][1], H and R differ: 1 + min(0, 1, 1) = 1, replace H with R.
Fill the other 14 cells the same way, row by row. Matches at R, O and S copy their diagonal for free. The corner says HORSE needs 3 edits to become ROS, and no shorter edit script exists.
Walk back from the corner to [0][0]. Each step names one edit: replace H with R, delete R, delete E. HORSE → RORSE → ROSE → ROS. Diagonal steps on a match are free.
Cost
For words of length m and n the table has (m + 1)(n + 1) cells, here 6 × 4 = 24, and each takes constant work. Time and space are O(mn). For the number alone, keeping two rows cuts space to O(n).
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.