Dynamic programming · 5 / 15 Theory

DP on strings

With two strings the state is usually (i, j): the first i characters of one and the first j of the other. That is how the longest common subsequence and the edit distance are solved.

def lcs(a, b):
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1          # they match: the subsequence grows
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[-1][-1]

print(lcs("abcde", "ace"))                  # 3

def edit_distance(a, b):
    previous = list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        current = [i]
        for j in range(1, len(b) + 1):
            cost = 0 if a[i - 1] == b[j - 1] else 1
            current.append(min(previous[j] + 1, current[j - 1] + 1, previous[j - 1] + cost))
        previous = current
    return previous[-1]

print(edit_distance("kitten", "sitting"))   # 3
  • LCS: if the last characters match, the best of (i-1, j-1) grows; if not, take the best between dropping one or the other.
  • Edit distance: from three neighbours, choose the smallest between deleting, inserting or replacing (cost 0 if they match).
  • If in each row you only need the previous one, keep two rows instead of the whole table: memory goes down from O(n·m) to O(m).
  • Segmenting with a dictionary: can[i] is true if there is a j < i with can[j] and text[j:i] in the dictionary.

You practice it in Longest common subsequence, Edit distance and Segment with a dictionary.