ENع
→LCS and edit distance
الدرس 41 · Dynamic programming and backtracking

Longest common subsequence and edit distance

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

15 دقيقة11 خطوة5 أسئلةAdvanced
عن هذا الدرس

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.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 41 · تفاعلي
01 / 11

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
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. 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
  2. One 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  ·  ·  ·
  3. 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  ·  ·  ·
  4. 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  ·  ·  ·
  5. 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")
    2
  6. Walk 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"
  7. 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  ·  ·  ·
  8. 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  ·  ·  ·
  9. 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")
    3
  10. Walk 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 → ROS
  11. Cost: 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

اختبار يتاح بعد الخطوة الأخيرة.