Data Structures & AlgorithmsHardProduct company OA

Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b).

Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b).
def lcs(a, b):
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] == b[j-1] else max(dp[i-1][j], dp[i][j-1])
    return dp[-1][-1]
def scs_len(a, b):
    return len(a) + len(b) - lcs(a, b)
print(scs_len("geek", "eke"), scs_len("abc", "def"), scs_len("night", "thing"))
What is printed?
  1. A. 4 6 8
  2. B. 5 3 8
  3. C. 5 6 7
  4. D. 5 6 8

Correct answer: D. 5 6 8

Characters of a common subsequence can be shared; everything else must appear separately. "geek"/"eke": LCS "ek" (2) → 4 + 3 − 2 = 5 (e.g. "geeke"). No common letters → 3 + 3 = 6. "night"/"thing": LCS length 2 (e.g. "ng") → 8; anagrams do not share more just because they use the same letters. O(m·n).

More Coding Interview Problems questions

Exams that ask this topic