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?- A. 99 97
- B. 198 194
- C. 194 194
- 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
- Problem: Find the longest bitonic subsequence (strictly increasing then strictly decreasing; either part may be empty) using LIS from the…
- Problem: Numbers whose only prime factors are 2, 3 and 5 (1 included) are generated in order with three pointers. python def ugly(n): u =…
- Problem: A chess knight hops on a phone keypad (1-9 in a 3 × 3 grid, 0 below 8). Count the distinct numbers of length n it can dial (start…
- Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two…
- Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can…
- Problem: Wildcard matching over the whole string: '?' matches any one character, '' matches any sequence (including empty). python def…