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?
  1. A. 4 4
  2. B. 5 5
  3. C. 4 5
  4. 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

Exams that ask this topic