ProgrammingVery hardGATE CS · Competitive coding (CP)

What is the length of the longest common subsequence of ABCBDAB and BDCABA? The program computes it by plain recursion without a table. What is printed?

What is the length of the longest common subsequence of ABCBDAB and BDCABA? The program computes it by plain recursion without a table. What is printed?
#include <stdio.h>
const char *X = "ABCBDAB", *Y = "BDCABA";
int lcs(int i, int j) {
    if (X[i] == '\0' || Y[j] == '\0') return 0;
    if (X[i] == Y[j]) return 1 + lcs(i + 1, j + 1);
    int a = lcs(i + 1, j), b = lcs(i, j + 1);
    return a > b ? a : b;
}
int main(void) {
    printf("%d", lcs(0, 0));
}
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 6

Correct answer: B. 4

The recursion returns the longest common subsequence length of the two suffixes, and for these strings it is 4, for example BCBA.

More C Programming questions

Exams that ask this topic