Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted.
Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted.
def cost(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1): dp[i][n] = dp[i+1][n] + ord(a[i])
for j in range(n - 1, -1, -1): dp[m][j] = dp[m][j+1] + ord(b[j])
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
dp[i][j] = dp[i+1][j+1] if a[i] == b[j] else min(ord(a[i]) + dp[i+1][j], ord(b[j]) + dp[i][j+1])
return dp[0][0]
print(cost("dog", "god"))What is printed?- A. 428
- B. 406
- C. 422
- D. 628
Correct answer: B. 406
'dog' and 'god' have no common subsequence of length 2 (do, dg, og versus go, gd, od), so only one letter can survive. Keeping the letter with the largest code, 'o' (111), deletes d and g from both: 2 × (100 + 103) = 406; keeping d or g costs 422 or 428.
More Coding Interview Problems questions
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second…
- Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times. python…
- Problem: AND of every integer in the range [lo, hi]. python def rangeand(lo, hi): shift = 0 while lo != hi: lo >>= 1; hi >>= 1; shift += 1…
- Problem: Ugly numbers have no prime factors other than 2, 3 and 5. Generate them in order with three pointers. python def ugly(n): u =…
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses. python def frac(n, d): q, r = divmod(n, d); s =…
- Generating all permutations of n distinct items with backtracking and copying each complete permutation into the result list costs how…