ProgrammingVery hardCAT · MBA placement

The longest common subsequence (LCS) of "ABCBDAB" and "BDCABA" is computed by the standard table. The procedure below prints its length. What is printed?

The longest common subsequence (LCS) of "ABCBDAB" and "BDCABA" is computed by the standard table. The procedure below prints its length. What is printed?
dp[i][j] = dp[i-1][j-1] + 1 if the letters match, else max(dp[i-1][j], dp[i][j-1])
Print dp[m][n]
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 6

Correct answer: C. 4

The LCS is BCBA (or BDAB), which has length 4. Ignoring the max over skipped characters undercounts to 3, the longest common contiguous run is only 2 (AB), and the length of the shorter string gives 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic