-1

Let the input sequences be X[0..m-1] and Y[0..n-1] of lengths m and n respectively. And let L(X[0..m-1], Y[0..n-1]) be the length of LCS of the two sequences X and Y. Following is the recursive definition of L(X[0..m-1], Y[0..n-1]).

If last characters of both sequences match (or X[m-1] == Y[n-1]) then L(X[0..m-1], Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])

If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then

L(X[0..m-1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2]) )

How to solve the problem if the lengths are different ? and how to print the respective sequences

Jithin
  • 1,692
  • 17
  • 25
  • You just described the algorithm to solve the question? The lengths of the strings don't actually matter. – Primusa Nov 01 '19 at 17:03
  • I'm not aware of a standard algorithm for the longest common subsequence problem which requires the two sequences to have the same length. – kaya3 Nov 01 '19 at 17:05
  • Those two strings are not a common subsequence; they don't match, and will fail the algorithm. You also mention "how to print the respective subsequences" -- you don't, as the two are identical. You print the resulting single value. – Prune Nov 01 '19 at 17:32
  • How would you print the longest common subsequence ?? – Srihari Athiyarath Nov 03 '19 at 01:25

1 Answers1

0

It doesn't matter if the length of input strings are same or not, and this is taken care by the base case of recursion.

if (m == 0 || n == 0) 
    return 0; 

If we reach the end of any one of the string, the recursion stops and unwinds from there.

Also the example you mentioned in comment:

ABCEFG and ABXDE First we compare last character from both string. In this case, they are not same.

So we try two cases:

  • Remove last character from first string and compare it with second.
  • Remove last character from second string and compare it with first.

And return the max from both cases.

(As a side note, if the last character had matched, we would add 1 to our answer and remove the last character from both strings)

This process continues till any of the string reaches it's end, in which case, the base case of your recursion is satisfied and the recursion returns.

So it doesn't matter if the original length of string is same or not.

Sumit Jha
  • 2,095
  • 2
  • 21
  • 36