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?- A. 2 1
- B. 1 0
- C. 2 2
- 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
- Problem: Fibonacci modulo 10⁹ + 7 by 2 × 2 matrix exponentiation in O(log n). python MOD = 109 + 7 def mul(A, B): return [[(A[0][0]B[0][0]…
- Problem: Count balanced parenthesis strings with n pairs whose nesting depth never exceeds d (DP over position and current depth). python…
- Problem: Count integers in [1, N] whose digits sum to S, with a digit DP over (position, sum so far, tight). python from functools import…
- Problem: Assign 4 workers to 4 jobs (one each) to minimise total cost, with a DP over the bitmask of used jobs. python cost = [[9, 2, 7…
- Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP. python from collections…
- Edge case: greedy coin change versus DP when the coin system is not canonical. python def greedy(coins, x): cnt = 0 for c in sorted(coins…