Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Return the length of the shortest string that contains both a and b as subsequences.

Problem: Return the length of the shortest string that contains both a and b as subsequences.
def scs(a, b):
    m, n = len(a), len(b)
    L = [[0] * (n + 1) for _ in range(m + 1)]
    for i in range(m):
        for j in range(n):
            L[i+1][j+1] = L[i][j] + 1 if a[i] == b[j] else max(L[i][j+1], L[i+1][j])
    return m + n - L[m][n]
print(scs("STUDYCLIP", "CLIPSTUDY"))
What is printed?
  1. A. 14
  2. B. 18
  3. C. 9
  4. D. 13

Correct answer: D. 13

Shortest common supersequence = |a| + |b| − LCS. The LCS here is 'STUDY' (length 5, longer than 'CLIP'), so 9 + 9 − 5 = 13. Using 'CLIP' as the LCS gives 14; just concatenating gives 18.

More Coding Interview Problems questions

Exams that ask this topic