Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments.
Problem: Compare the longest common SUBSTRING (contiguous) with the longest common SUBSEQUENCE of two log fragments.
def lcsub(a, b):
best = 0; dp = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
new = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
new[j] = dp[j - 1] + 1; best = max(best, new[j])
dp = new
return best
def lcseq(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]
print(lcsub("xabcdzbcde", "pbcdeqabc"), lcseq("xabcdzbcde", "pbcdeqabc"))What is printed?- A. 4 4
- B. 5 5
- C. 4 5
- D. 3 5
Correct answer: C. 4 5
For substrings a mismatch resets the cell to 0 (the run must be contiguous) and the answer is the maximum cell anywhere: "bcde" → 4. For subsequences a mismatch carries max(top, left), allowing gaps: "bcdbc" (b c d from "bcde", then b c from "abc") has length 5. Both are O(m·n); confusing the two recurrences is the classic mistake.
More Coding Interview Problems questions
- Problem: Find the length of the shortest string that contains both a and b as subsequences: |a| + |b| − LCS(a, b). python def lcs(a, b)…
- 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 =…