Data Structures & AlgorithmsHardCodeforces Div2 C/D · Amazon SDE OA

Two strings are "intention" and "execution". Compute the minimum cost to turn the first into the second, where insertion and deletion cost 1 each and substitution costs 2 (so a substitution is never cheaper than a delete plus an insert).

Two strings are "intention" and "execution". Compute the minimum cost to turn the first into the second, where insertion and deletion cost 1 each and substitution costs 2 (so a substitution is never cheaper than a delete plus an insert).
a,b="intention","execution"
n,m=len(a),len(b)
d=[[0]*(m+1) for _ in range(n+1)]
for i in range(n+1): d[i][0]=i
for j in range(m+1): d[0][j]=j
for i in range(1,n+1):
    for j in range(1,m+1):
        sub = 0 if a[i-1]==b[j-1] else 2
        d[i][j]=min(d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1]+sub)
print(d[n][m])
What is printed?
  1. A. 5
  2. B. 8
  3. C. 10
  4. D. 9

Correct answer: B. 8

Substitution costs 2, so the DP uses the cheaper of delete plus insert and a 2-cost substitution, which makes the answer equal the indel distance. Unit substitution gives the classic Levenshtein value, a position-by-position comparison ignores shifted alignment, and doubling the indel costs changes the trade-off.

More Coding Interview Problems questions

Exams that ask this topic