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?- A. 14
- B. 18
- C. 9
- 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
- Problem: The reflected binary Gray code of i is i ^ (i >> 1). At which position of the 3-bit Gray sequence does the code 6 (110) appear?…
- Problem: A permissions engine isolates bits of a mask. python x = 88 print(x & -x, x & (x - 1)) What is printed?
- Problem: Rearrange the digits of a version list into the next lexicographically greater permutation. python def nxt(a): i = len(a) - 2…
- An analytics service holds a static array of n = 10⁵ integers and must answer q = 10⁶ queries 'minimum of a[l..r]' as fast as possible…
- Given n = 5 × 10⁴ integers, count pairs i < j with a[i] > 2·a[j]. Which approach is correct and efficient?
- Problem: Evaluate a reverse-Polish expression. The specification says division must truncate toward zero (as in C or Java). python def…