We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Fast Edit Distance – Review

You can refer to the following example implementation when answering these questions.

def edit_distance(str1: str, str2: str) -> int:
    table: list[list[int]] = []
    for _ in range(0, len(str1) + 1):
        row: list[int] = []
        for _ in range(0, len(str2) + 1):
            row.append(0)
        table.append(row)

    for i in range(0, len(table)):
        for j in range(0, len(table[i])):
            # First string is empty (up to this point)
            # Distance is length of second string (up to this point)
            if i == 0:
                table[i][j] = j

            # Second string is empty (up to this point)
            # Distance is length of first string (up to this point)
            elif j == 0:
                table[i][j] = i

            # Last characters are same
            # Distance is unchanged from one character earlier
            elif str1[i - 1] == str2[j - 1]:
                table[i][j] = table[i - 1][j - 1]

            # Last characters are different
            # Find the minimum-cost operation
            else:
                table[i][j] = 1 + min(
                    table[i][j - 1],  # Insert
                    table[i - 1][j],  # Delete
                    table[i - 1][j - 1],  # Substitute
                )

    return table[-1][-1]