Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Find the length of the longest common subsequence of two version strings.

Problem: Find the length of the longest common subsequence of two version strings.
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]
print(lcs("ABCBDAB", "BDCABA"), lcs("abc", "def"))
What is printed?
  1. A. 3 0
  2. B. 4 0
  3. C. 5 0
  4. D. 4 1

Correct answer: B. 4 0

dp[i][j] = LCS of the first i and j characters. One LCS is BCBA (or BDAB) of length 4. Subsequences need not be contiguous – the longest common substring here is only 2. O(m·n) time and space (O(min) with two rows).

More Coding Interview Problems questions

Exams that ask this topic