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?- A. 5
- B. 8
- C. 10
- 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
- A staircase is climbed with steps of size 1, 3 or 4 (order of steps matters). How many distinct ordered sequences of steps reach exactly…
- Forty-one people stand in a circle numbered 1 to 41. Starting from person 1, every third person is removed, repeatedly, counting continues…
- Compute the sum of the prefix-function (KMP failure) array of the string "abacabab", where pi[i] is the length of the longest proper…
- A directed weighted graph has edges 0→1 (2), 0→2 (2), 1→3 (1), 2→3 (1), 1→4 (4), 2→4 (5), 3→4 (3), 3→5 (4), 4→5 (1). Count the number of…
- On vertices 0..4 a weighted directed graph has these edges, stored in the order shown in the code: (3→4, −2), (2→4, 8), (4→1, 2), (1→3…
- A task graph has six nodes 0 to 5 and dependencies 5→0, 4→0, 4→1, 5→2, 2→3, 3→1 (an edge u→v means u must finish before v). Among all…