ProgrammingHardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
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):
            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])
    return dp[-1][-1]
print(lcs('ABCBDAB', 'BDCABA'))
  1. A. 3
  2. B. 5
  3. C. 4
  4. D. 2

Correct answer: C. 4

One longest common subsequence is BCBA, with length 4, so the bottom-right DP cell is 4. Where the characters differ, the cell takes the larger of its two neighbours.

More Python Programming questions

Exams that ask this topic