Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Find the minimum number of insert, delete or replace operations to convert one word to another (edit distance).

Problem: Find the minimum number of insert, delete or replace operations to convert one word to another (edit distance).
def edit(a, b):
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m + 1): dp[i][0] = i
    for j in range(n + 1): dp[0][j] = 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]
            else: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
    return dp[m][n]
print(edit("sunday", "saturday"), edit("", "abc"), edit("flaw", "lawn"))
What is printed?
  1. A. 4 3 2
  2. B. 3 0 2
  3. C. 3 3 3
  4. D. 3 3 2

Correct answer: D. 3 3 2

sunday → saturday: insert a, insert t, replace n with r = 3. From the empty string, insert all 3 letters (base row). flaw → lawn: delete f, append n = 2. The base cases dp[i][0] = i and dp[0][j] = j are essential; leaving them 0 undercounts. O(m·n).

More Coding Interview Problems questions

Exams that ask this topic