Data Structures & AlgorithmsHardProduct company OA

Problem: Make two strings equal by deleting characters; the cost is the sum of ASCII codes of deleted characters. Minimise it (a weighted edit-distance DP).

Problem: Make two strings equal by deleting characters; the cost is the sum of ASCII codes of deleted characters. Minimise it (a weighted edit-distance DP).
def ascii_del(a, b):
    m, n = len(a), len(b)
    dp = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(1, m + 1): dp[i][0] = dp[i - 1][0] + ord(a[i - 1])
    for j in range(1, n + 1): dp[0][j] = dp[0][j - 1] + ord(b[j - 1])
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            dp[i][j] = dp[i-1][j-1] if a[i-1] == b[j-1] else min(dp[i-1][j] + ord(a[i-1]), dp[i][j-1] + ord(b[j-1]))
    return dp[m][n]
print(ascii_del("cab", "acb"), ascii_del("ab", "ba"))
What is printed?
  1. A. 99 97
  2. B. 198 194
  3. C. 194 194
  4. D. 194 196

Correct answer: C. 194 194

Keeping a common subsequence costs the ASCII sum of everything else. "cab" vs "acb": keep "cb" by deleting both 'a's (97 + 97 = 194) – cheaper than keeping "ab" by deleting both 'c's (198), even though both LCSs have length 2. "ab" vs "ba": deleting the two 'a's (194) beats deleting the two 'b's (196). O(m·n).

More Coding Interview Problems questions

Exams that ask this topic