Python 3D Academyবাংলা

Longest common subsequence

🌍 In real life. Nadia writes the first draft of an essay, then a second draft. Her teacher wants to see what changed. A compare tool (the "track changes" of a word processor, or diff for programmers) finds the longest list of lines that both drafts have in the same order; every other line was deleted from the first draft or added in the second. That list is the drafts' longest common subsequence.

The idea in one sentence: let dp[i][j] be the LCS of the first i items of a and the first j items of b; if the last two items match they both join it, and if not, one of them is not in it, so drop each in turn and keep the better.

Its words:

  • subsequence: items taken in order, with gaps allowed: CD is a subsequence of CODE, DC is not
  • common subsequence: one that both a and b contain
  • prefix: the first i items, a[:i]; the table has a row for every prefix of a, the empty one included
  • trace back: walk from the answer cell to rebuild the subsequence itself

Step by step:

  1. make a (m + 1) × (n + 1) table; row 0 and column 0 are 0 (an empty prefix has nothing in common)
  2. if a[i − 1] == b[j − 1]: dp[i][j] = dp[i − 1][j − 1] + 1
  3. otherwise: dp[i][j] = max(dp[i − 1][j], dp[i][j − 1])
  4. the length is dp[m][n]; to get the items, walk back: diagonally on a match, else towards the bigger neighbour

Here the "drafts" are two short words, one letter standing for one line:

Why the rule is right. Look at the last items x = a[i − 1] and y = b[j − 1]. If x == y, some longest common subsequence ends with that item in both, because any one that doesn't could swap its last item for this pair. If x != y, a common subsequence can't end with both, so it leaves out x (the answer for a[:i − 1] and b[:j], the cell above) or leaves out y (the cell to the left). The better of the two is the answer.

What it costs, by counting. One cell for every pair of prefixes: two 1,000-line drafts give 1,001 × 1,001, about 1,000,000 cells. Trying every subsequence of one draft instead means 2 to the power 1,000 of them. In Big-O: O(m × n) time and O(m × n) memory for words of lengths m and n.

def lcs_length(a, b):
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]   # dp[i][j]: the LCS of a[:i] and b[:j]
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1      # both last items join the subsequence
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])   # drop one of them
    return dp[m][n]

def lcs_items(a, b):
    m, n = len(a), len(b)
    dp = [[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]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    i, j, kept = m, n, []
    while i > 0 and j > 0:                       # walk back from the answer
        if a[i - 1] == b[j - 1]:
            kept.append(a[i - 1])
            i, j = i - 1, j - 1
        elif dp[i - 1][j] >= dp[i][j - 1]:
            i -= 1
        else:
            j -= 1
    return kept[::-1]                            # found from the end, so turn it round

print(lcs_length("CODE", "COLD"), lcs_items("CODE", "COLD"))
first = ["Dhaka is big.", "It is busy.", "I like it."]
second = ["Dhaka is big.", "It rains a lot.", "I like it."]
print(lcs_items(first, second))

Mistakes and edge cases.

  • subsequence or substring: a substring has no gaps (COD in CODE); the LCS allows gaps, so COD of CODE and COLD counts even though L sits between O and D
  • an off-by-one: row i is the prefix a[:i], so its last letter is a[i − 1], not a[i]
  • the rebuilt list comes out backwards: the walk starts at the end, so reverse it
  • several answers: AB and BA have two longest common subsequences, A and B; on a tie, different walks give different answers of the same length
  • lists work too: the same code compares lists of lines, because it only indexes and compares items

Quiz

  1. Which is a subsequence of PYTHON?

    • PTN
    • NOP
    • PYY
  2. What does this print?

    def lcs_length(a, b):
        m, n = len(a), len(b)
        dp = [[0] * (n + 1) for _ in range(m + 1)]   # dp[i][j]: the LCS of a[:i] and b[:j]
        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if a[i - 1] == b[j - 1]:
                    dp[i][j] = dp[i - 1][j - 1] + 1      # both last items join the subsequence
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])   # drop one of them
        return dp[m][n]
    
    print(lcs_length("ABCBDAB", "BDCABA"))
  3. a[i − 1] and b[j − 1] differ. What is dp[i][j]?

    • max(dp[i − 1][j], dp[i][j − 1])
    • dp[i − 1][j − 1] + 1
    • 0
  4. What does this print?

    def lcs_items(a, b):
        m, n = len(a), len(b)
        dp = [[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]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
        i, j, kept = m, n, []
        while i > 0 and j > 0:                       # walk back from the answer
            if a[i - 1] == b[j - 1]:
                kept.append(a[i - 1])
                i, j = i - 1, j - 1
            elif dp[i - 1][j] >= dp[i][j - 1]:
                i -= 1
            else:
                j -= 1
        return kept[::-1]                            # found from the end, so turn it round
    
    print(lcs_items("ABC", "CAB"))
  5. lcs_length("AB", "B") stops with an IndexError. Which line is wrong?

    def lcs_length(a, b):
        m, n = len(a), len(b)
        dp = [[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] == b[j]:
                    dp[i][j] = dp[i - 1][j - 1] + 1
                else:
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
        return dp[m][n]

Coding tasks

  1. Write lcs_length(a, b): the length of the longest common subsequence of a and b, which may be strings or lists.

  2. Write lcs_items(a, b): return the items of a longest common subsequence of a and b, as a list in order. (Every test has only one longest common subsequence.)