Longest Common Subsequence | Introduction & LCS Length

The longest common subsequence (LCS) problem is the problem of finding the longest subsequence that is present in given two sequences in the same order. i.e. find a longest sequence which can be obtained from the first original sequence by deleting some items, and from the second original sequence by deleting other items.


 

The problem differs from problem of finding common substrings. Unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences.

For example, consider the two following sequences X and Y

X: ABCBDAB
Y: BDCABA


The length of LCS is 4
LCS are BDAB, BCAB and BCBA

 

 
A Naive solution would be to check if every subsequence of X[1..m] to see if it is also a subsequence of Y[1..n]. As there are 2m subsequences possible of X, the complexity of this solution would be O(n.2m).

 
The LCS problem has an optimal substructure. That means the problem can be broken down into smaller, simple “subproblems”, which can be broken down into yet simpler subproblems, and so on, until, finally, the solution becomes trivial.
 

1. Let us consider two sequences X and Y of length m and n that both end in the same element.
To find their LCS, shorten each sequence by removing the last element, find the LCS of the shortened sequences, and to that LCS append the removed element. So we can say that


LCS(X[1..m], Y[1..n]) = LCS(X[1..m-1], Y[1..n-1]) + X[m]   if X[m] = Y[n]

 

2. Now suppose that the two sequences do not end in the same symbol.
Then the LCS of X and Y is the longer of the two sequences LCS(X[1..m-1], Y[1..n]) and LCS(X[1..m], Y[1..n-1]). To understand this property, let’s consider the two following sequences

X: ABCBDAB (n elements)
Y: BDCABA  (m elements)

 

The LCS of these two sequences either ends with a B (the last element of sequence X) or does not.

Case 1: If LCS ends with a B, then it cannot end with a A and we can remove the A from sequence Y and the problem reduces to LCS(X[1..m], Y[1..n-1]).

Case 2: If LCS does not end with a B, then we can remove B from the sequence X and the problem reduces to LCS(X[1..m-1], Y[1..n]). For example,

LCS(‘ABCBDAB’, ‘BDCABA’) = maximum (LCS(‘ABCBDA’, ‘BDCABA’),
                                    LCS(‘ABCBDAB’, ‘BDCAB’))

LCS(‘ABCBDA’, ‘BDCABA’) = LCS(‘ABCBD’, ‘BDCAB’) + ‘A’
LCS(‘ABCBDAB’, ‘BDCAB’) = LCS(‘ABCBDA’, ‘BDCA’) + ‘B’

LCS(‘ABCBD’, ‘BDCAB’) = maximum (LCS(‘ABCB’, ‘BDCAB’), LCS(‘ABCBD’, ‘BDCA’))
LCS(‘ABCBDA’, ‘BDCA’) = LCS(‘ABCBD’, ‘BDC’) + ‘A’

and so on..

Below solution finds the length of LCS of sequences X[0..m-1] and Y[0..n-1] recursively by using optimal substructure property of LCS problem.

C++

Download   Run Code

Output:

The length of LCS is 4

Java

Download   Run Code

Output:

The length of LCS is 4

 
The worst case time complexity of above solution is O(2(m+n)). The worst case happens when there is no common subsequence present in X and Y (i.e. LCS is 0) and each recursive call will end up in two recursive calls.
 

 
The LCS problem exhibits overlapping subproblems. A problem is said to have overlapping subproblems if the recursive algorithm for the problem solves the same subproblem over and over rather than always generating new subproblems.

Let us consider recursion tree for two sequences of length 6 and 8 whose LCS is 0.

  longest common subsequence recursion tree

As we can see, the same sub-problems (highlighted in same color) are getting computed again and again. We know that problems having optimal substructure and overlapping subproblems can be solved by dynamic programming, in which subproblem solutions are memoized rather than computed again and again. This method is illustrated below in C++ and Java –

C++

Download   Run Code

Output:

The length of LCS is 4

Java

Download   Run Code

Output:

The length of LCS is 4

 
The time complexity of above solution is O(mn) and auxiliary space used by the program is O(mn). Note that we can also use array instead of map. Check implementation here.
 

 
Above Memoized version follows the top-down approach, since we first break the problem into subproblems and then calculate and store values. We can also solve this problem in bottom-up manner. In the bottom-up approach, we calculate the smaller values of LCS(i, j) first, then build larger values from them.


            | 0                                          if i == 0 or j == 0
LCS[i][j] = | LCS[i – 1][j – 1] + 1                      if X[i-1] == Y[j-1]
            | longest(LCS[i – 1][j], LCS[i][j – 1])      if X[i-1] != Y[j-1]

 

Let X be “XMJYAUZ” and Y be “MZJAWXU”. The longest common subsequence between X and Y is “MJAU”. The table below is generated by the function LCSLength, shows the lengths of the longest common subsequences between prefixes of X and Y. The ith row and jth column shows the length of the LCS of substring X[0..i-1] and Y[0..j-1].

  longest common subsequence array

C++

Download   Run Code

Output:

The length of LCS is 4

Java

Download   Run Code

Output:

The length of LCS is 4

 
The time complexity of above solution is O(mn) and auxiliary space used by the program is O(mn). The space compexity of above solution can be improved to O(n) as calculating LCS of a row of the LCS table requires only the solutions to the current row and the previous row.

 

Applications of LCS problem:

The longest common subsequence problem forms the basis of data comparison programs such as the diff utility and use in field of bioinformatics. It is also widely used by revision control systems such as Git.

 
Exercise:

1. Extend the solution for finding length of LCS for K-sequences

2. Write space optimized code for iterative version.

 
Recommended Read: Longest Common Subsequence (Finding all LCS)

 
References: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
 

1 Star2 Stars3 Stars4 Stars5 Stars (12 votes, average: 5.00 out of 5)
Loading...

 
Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
newest oldest most voted
Notify of
Geek
Guest

Good post!

md. saiful islam
Guest

really helpful

mohan
Guest

good

Anne
Guest

Thanks! This helped me to get started with dynamic programming.

Vik
Guest

Nice

Rahul
Guest

Thanks 🙂
Great place to start dynamic programming.

Andre
Guest

Please make your page copyable so I and people like me can read it with my screen reader.

Andy
Guest

It would of course be more appropriate if they actually did that (since keeping text from being selectable is simply ridiculous…) but in the meantime, you could install this:
https://greasyfork.org/en/scripts/26305-enable-text-selection-disabled-by-css/code

Ovi Poddar
Guest

it’s an amazing platform to learn dp ! loved it !