Data Structures & AlgorithmsModerateTCS NQT · DP warm-up

Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'?

Problem: What is the length of the longest common subsequence of 'ABCBDAB' and 'BDCABA'?
a, b = 'ABCBDAB', 'BDCABA'
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
        else:
            dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
print(dp[-1][-1])
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: B. 4

A longest common subsequence is BCBA, which appears in both strings in order, so the DP gives 4. Taking the longest common substring instead gives a smaller value.

More Coding Interview Problems questions

Exams that ask this topic