Longest common subsequence and edit distance
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
Two classic string problems share one table. Compare HORSE with ROS: cell [i][j] answers the question for the first i letters of each word, and every cell is built from three neighbours filled before it. With one rule the table finds the longest common subsequence (OS, length 2); with another it finds the edit distance (3: HORSE → RORSE → ROSE → ROS). Walking back from the corner turns the numbers into the actual letters or edits. The Software lesson "Dynamic programming" covers memoisation and filling a table bottom-up; here we use those ideas on two inputs at once.
Letters in order, gaps allowed
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.
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
اقرأ الدرس خطوة بخطوة
Letters in order, gaps allowed
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.
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 allowedOne cell per pair of prefixes
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.
L[i][j] = LCS length of a[:i] and b[:j] L[0][j] = 0, L[i][0] = 0 (empty prefix) table size (5 + 1) × (3 + 1) = 24 cells start: ∅ R O S ∅ 0 0 0 0 H 0 · · · O 0 · · · R 0 · · · S 0 · · · E 0 · · ·Letters match: diagonal + 1
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.
cell [2][2]: a[1] = "O", b[1] = "O" → match L[2][2] = L[1][1] + 1 = 0 + 1 = 1 so far: ∅ R O S ∅ 0 0 0 0 H 0 0 0 0 O 0 0 1 · R 0 · · · S 0 · · · E 0 · · ·No match: take the bigger
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.
cell [2][3]: a[1] = "O", b[2] = "S" → no match L[2][3] = max(L[1][3], L[2][2]) = max(0, 1) = 1 so far: ∅ R O S ∅ 0 0 0 0 H 0 0 0 0 O 0 0 1 1 R 0 · · · S 0 · · · E 0 · · ·Fill the rest
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.
full table: ∅ R O S ∅ 0 0 0 0 H 0 0 0 0 O 0 0 1 1 R 0 1 1 1 S 0 1 1 2 E 0 1 1 2 def lcs(a, b): m, n = len(a), len(b) L = [[0] * (n + 1) for _ in range(m + 1)] for i in range(1, m + 1): for j in range(1, n + 1): if a[i-1] == b[j-1]: L[i][j] = L[i-1][j-1] + 1 else: L[i][j] = max(L[i-1][j], L[i][j-1]) return L[m][n] >>> lcs("HORSE", "ROS") 2Walk back to read it
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.
walk from [5][3]: [5][3] no match, up ≥ left → go ↑ [4][3] match "S" → keep it, go ↖ [3][2] no match, up ≥ left → go ↑ [2][2] match "O" → keep it, go ↖ [1][1] no match, up ≥ left → go ↑ LCS = "OS"Edit distance: same table
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.
D[i][j] = fewest edits turning a[:i] into b[:j] D[0][j] = j (insert j letters) D[i][0] = i (delete i letters) start: ∅ R O S ∅ 0 1 2 3 H 1 · · · O 2 · · · R 3 · · · S 4 · · · E 5 · · ·A new rule: 1 + cheapest
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.
cell [1][1]: a[0] = "H", b[0] = "R" → no match D[1][1] = 1 + min(D[0][0], D[0][1], D[1][0]) = 1 + min(0, 1, 1) = 1 (replace) so far: ∅ R O S ∅ 0 1 2 3 H 1 1 · · O 2 · · · R 3 · · · S 4 · · · E 5 · · ·Fill: distance 3
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.
full table: ∅ R O S ∅ 0 1 2 3 H 1 1 2 3 O 2 2 1 2 R 3 2 2 2 S 4 3 3 2 E 5 4 4 3 def edit_distance(a, b): m, n = len(a), len(b) D = [[0] * (n + 1) for _ in range(m + 1)] for i in range(m + 1): D[i][0] = i # delete all i letters for j in range(n + 1): D[0][j] = j # insert all j letters for i in range(1, m + 1): for j in range(1, n + 1): if a[i-1] == b[j-1]: D[i][j] = D[i-1][j-1] else: D[i][j] = 1 + min(D[i-1][j-1], # replace D[i-1][j], # delete D[i][j-1]) # insert return D[m][n] >>> edit_distance("HORSE", "ROS") 3Walk back: the edits
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.
walk from [5][3]: [5][3] delete "E", go ↑ [4][3] match "S" → free, go ↖ [3][2] delete "R", go ↑ [2][2] match "O" → free, go ↖ [1][1] replace "H" with "R", go ↖ HORSE → RORSE → ROSE → ROSCost: one pass over the table
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).
cells: (m + 1)(n + 1) = 6 × 4 = 24 work per cell: one compare + max or min of 3 time O(mn), space O(mn) only the number? keep the previous row and the current one: space O(n) walking back needs the whole table
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01Which of these is a subsequence of HORSE but not a substring of it?
HOE keeps H, O and E in order but skips R and S, so it is a subsequence. ORS, RSE and HOR are runs of letters next to each other: substrings, and therefore subsequences too.
02In the LCS table, a[i-1] and b[j-1] are different letters. What goes in L[i][j]?
The two last letters cannot both be in the LCS, so drop one of them: the cell above drops a's letter, the cell to the left drops b's. Keep whichever answer is bigger.
03In the edit-distance table, which neighbour stands for deleting the letter a[i-1]?
After deleting a[i-1], the first i - 1 letters of a still have to become the first j letters of b: that is D[i-1][j], plus 1 for the delete. The diagonal is a replace, the left cell an insert.
04What is the edit distance between HORSE and ROS, and what is their LCS length?
The tables end with D[5][3] = 3 (replace H with R, delete R, delete E) and L[5][3] = 2 (OS). Without replace, the fewest edits would be 5 + 3 − 2·2 = 4.
05You need only the edit distance of two strings of lengths m and n, not the edits themselves. How much memory does the table method really need?
Each row is computed from the row above it alone, so keeping the previous and the current row is enough: O(n) space, still O(mn) time. Walking back to list the edits needs the whole table.
المسرد
- Subsequence
- Some letters of a sequence kept in their original order, with any others skipped. HOE is a subsequence of HORSE.
- Substring
- A run of letters that sit next to each other, like ORS in HORSE. Every substring is a subsequence, not the other way round.
- Longest common subsequence (LCS)
- The longest sequence that is a subsequence of both inputs. HORSE and ROS have two, OS and RS, both of length 2.
- Edit distance
- The fewest one-letter inserts, deletes and replaces that turn one string into another. Also called Levenshtein distance.
- Prefix
- The first i letters of a string; a[:i] in Python. The empty prefix has i = 0.
- Edit script
- A list of edits that turns one string into another, such as replace H with R, delete R, delete E.
- Traceback
- Walking back from the final cell to the start, following the neighbour each value came from, to rebuild the answer itself.
الملاحظات والمصادر
- 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.
- With only insert and delete (no replace), the fewest edits are m + n − 2·LCS: delete the letters of a that are not in the LCS and insert the letters of b that are not. For HORSE and ROS that is 5 + 3 − 2·2 = 4; allowing replace brings it down to 3.
- Checking every subsequence instead would mean up to 2^m of them for a word of length m. The table answers with (m + 1)(n + 1) cells.
- The Python functions in the detail panel are runnable as written: lcs("HORSE", "ROS") returns 2 and edit_distance("HORSE", "ROS") returns 3.
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 16: Dynamic Programming Subproblems (LCS, LIS, Coins), lecture notes
- MIT 6.006 Introduction to Algorithms (Fall 2011), Lecture 21: DP III: Parenthesization, Edit Distance, Knapsack
- MIT 6.006 (Fall 2011), Lecture 21 transcript
- Sedgewick and Wayne, LongestCommonSubsequence.java (Introduction to Programming in Java, §2.3)
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §14.4 and Problem 14-5
- Wagner–Fischer algorithm (Wagner and Fischer, 1974)
- Python documentation: Built-in functions (max, min, range)
اختبار يتاح بعد الخطوة الأخيرة.