Data Structures & AlgorithmsModerateTCS NQT · string round

Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'.

Problem: Find the length of the longest common substring (contiguous) of 'abcdef' and 'zcdemn'.
def lcs_sub(a, b):
    best = 0
    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):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
                best = max(best, dp[i][j])
    return best
print(lcs_sub('abcdef', 'zcdemn'))
What is printed?
  1. A. 2
  2. B. 4
  3. C. 3
  4. D. 5

Correct answer: C. 3

The shared contiguous block is 'cde', giving 3. A longest common subsequence would also allow gaps, which is why the DP resets on mismatch.

More Coding Interview Problems questions

Exams that ask this topic