Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Minimum number of single-character insertions plus deletions to turn a into b (no replacements).

Problem: Minimum number of single-character insertions plus deletions to turn a into b (no replacements).
def ins_del(a, b):
    m, n = len(a), len(b); L = [[0]*(n+1) for _ in range(m+1)]
    for i in range(m):
        for j in range(n):
            L[i+1][j+1] = L[i][j] + 1 if a[i] == b[j] else max(L[i][j+1], L[i+1][j])
    k = L[m][n]
    return m - k, n - k
print(*ins_del("heap", "pea"))
What is printed?
  1. A. 2 1
  2. B. 1 0
  3. C. 2 2
  4. D. 3 2

Correct answer: A. 2 1

Keep a longest common subsequence: 'ea' (length 2). Delete the other 4 − 2 = 2 letters of 'heap' (h, p) and insert 3 − 2 = 1 letter of 'pea' (the leading p): 2 deletions, 1 insertion. Edit distance with replacements would be smaller.

More Coding Interview Problems questions

Exams that ask this topic