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?- A. 4 3 2
- B. 3 0 2
- C. 3 3 3
- 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
- Problem: Count paths from the top-left to the bottom-right of a grid moving only right or down, where 1 marks a blocked cell. python def…
- Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down). python def minpath(g): R…
- Problem: Count the ways to decode a digit string where 'A' = 1 … 'Z' = 26. python def decode(s): prev2, prev1 = 1, (1 if s[0] != '0' else…
- Problem: Decide whether a string can be split into words from a dictionary. python def wb(s, words): W = set(words); dp = [True] + [False]…
- Problem: Return the maximum product of a contiguous subarray (values may be negative or zero). python def maxprod(a): hi = lo = best =…
- Problem: Can an array be split into two subsets with equal sums? python def cansplit(a): s = sum(a) if s % 2: return False reach = 1 for x…