in Algorithms edited by
9,115 views
32 votes
32 votes

A sub-sequence of a given sequence is just the given sequence with some elements (possibly none or all) left out. We are given two sequences $X[m]$ and $Y[n]$ of lengths $m$ and $n$, respectively with indexes of $X$ and $Y$ starting from $0$.

We wish to find the length of the longest common sub-sequence (LCS) of $X[m]$ and $Y[n]$ as $l(m, n)$, where an incomplete recursive definition for the function $I(i, j)$ to compute the length of the LCS of $X[m]$ and $Y[n]$ is given below:

l(i,j)  = 0, if either i = 0 or j = 0
        = expr1, if i,j > 0 and X[i-1] = Y[j-1]
        = expr2, if i,j > 0 and X[i-1] ≠ Y[j-1]

Which one of the following options is correct?

  1. $\text{expr1} = l\left(i-1, j\right) +1$

  2. $\text{expr1} = l\left(i, j-1\right)$

  3. $\text{expr2} = \max\left(l\left(i-1, j\right), l\left(i,j-1\right)\right)$

  4. $\text{expr2} = \max\left(l\left(i-1, j-1\right), l\left(i,j\right)\right)$

in Algorithms edited by
9.1k views

4 Comments

I suppose in Q 53. expr2 should have X[i-1]!=Y[j-1].

2
2
edited by

plz someone clearify!!

What about expr1???

max(l(i-1,j) , l(i,j-1)) +1 ?

0
0
I think it must be l(i-1, j-1) +1
2
2
I think expr1 = l(i-1,j-1)+1

and expr2=max(l(i-1,j),l(i,j-1))
1
1

2 Answers

37 votes
37 votes
Best answer

Answer is C. When the currently compared elements doesn't match, we have two possibilities for the LCS, one including X[i] but not Y[j] and other including Y[j] but not X[i].

/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
   if (m == 0 || n == 0)
     return 0;
   if (X[m-1] == Y[n-1])
     return 1 + lcs(X, Y, m-1, n-1);
   else
     return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
}
selected by

4 Comments

Sir, I've same doubt as asked by Radha Gogla ma'am. Could you please clarify it.
0
0
i have same doubt it has to be 1+c[i-2][j-2] otherwise algo will run into an infinite loop pls clarify in many areas it is given wrong
1
1
Its an algorithm not a piece of code that it will run for infinite times . These small things are taken care of while writing code.
2
2
24 votes
24 votes

Answer is C. 

When the currently compared elements doesn't match, we have two possibilities for the LCS, one including $X\left [ i \right ]$ but not $Y\left [ j \right ]$  and other including $Y\left [ j \right ]$ but not $X\left [ i \right ]$.

edited by
Answer:

Related questions