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?- A. 4 6 8
- B. 5 3 8
- C. 5 6 7
- 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
- Problem: Count the ways to roll n dice with k faces each so that the faces sum to target (mod 10⁹ + 7). python def dice(n, k, target…
- Problem: Picking a value v earns v points but deletes every v − 1 and v + 1 from the array; repeat until empty. Maximise points (reduces…
- Problem: Make two strings equal by deleting characters; the cost is the sum of ASCII codes of deleted characters. Minimise it (a weighted…
- 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…