Data Structures & AlgorithmsHardProduct Company SDE · CP practice

Problem: What is the length of the longest common subsequence of 'abcdef' and 'acebdf'? Run the DP.

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

Correct answer: A. 4

The common subsequence 'abdf' has length 4, and the DP finds the maximum.

More Coding Interview Problems questions

Exams that ask this topic