Data Structures & AlgorithmsHardProduct Company SDE · DP round

Problem: What is the Levenshtein distance between 'horse' and 'ros'? Run the DP.

Problem: What is the Levenshtein distance between 'horse' and 'ros'? Run the DP.
a, b = 'horse', 'ros'
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(len(a) + 1):
    dp[i][0] = i
for j in range(len(b) + 1):
    dp[0][j] = j
for i in range(1, len(a) + 1):
    for j in range(1, len(b) + 1):
        dp[i][j] = dp[i - 1][j - 1] if a[i - 1] == b[j - 1] else 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
print(dp[-1][-1])
What is printed?
  1. A. 2
  2. B. 3
  3. C. 4
  4. D. 5

Correct answer: B. 3

Replace h with r (rorse), delete the extra r (rose), then delete e (ros): 3 edits, and the DP confirms no 2-edit route exists.

More Coding Interview Problems questions

Exams that ask this topic