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?
  1. A. 428
  2. B. 406
  3. C. 422
  4. 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

Exams that ask this topic