Longest Common Subsequence Problem
The Longest Common Subsequence (LCS) problem is finding the longest subsequence present in given two sequences in the same order, i.e., find the 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 the problem of finding the longest common substring. Unlike substrings, subsequences are not required to occupy consecutive positions within the original string.
For example, consider the two following sequences, X
and Y
:
Y: BDCABA
The length of the LCS is 4
LCS are BDAB, BCAB, and BCBA
A naive solution is 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 time complexity of this solution would be O(n.2m), where m
is the length of the first string and n
is the length of the second string.
The LCS problem has 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’s 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 that LCS append the removed element. So, we can say that.
2. Now suppose that the two sequences does 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:
Y: BDCABA (m elements)
The LCS of these two sequences either ends with B
(the last element of the sequence X
) or does not.
B
, then it cannot end with A
, and we can remove A
from the sequence Y
, and the problem reduces to LCS(X[1…m], Y[1…n-1])
.
Case 2: If LCS does not end with B
, then we can remove B
from sequence X
and the problem reduces to LCS(X[1…m-1], Y[1…n])
. For example,
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…
The following solution in C++, Java, and Python find the length of LCS of sequences X[0…m-1]
and Y[0…n-1]
recursively using the LCS problem’s optimal substructure property:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> #include <string> using namespace std; // Function to find the length of the longest common subsequence of // sequences `X[0…m-1]` and `Y[0…n-1]` int LCSLength(string X, string Y, int m, int n) { // return if the end of either sequence is reached if (m == 0 || n == 0) { return 0; } // if the last character of `X` and `Y` matches if (X[m - 1] == Y[n - 1]) { return LCSLength(X, Y, m - 1, n - 1) + 1; } // otherwise, if the last character of `X` and `Y` don't match return max(LCSLength(X, Y, m, n - 1), LCSLength(X, Y, m - 1, n)); } int main() { string X = "ABCBDAB", Y = "BDCABA"; cout << "The length of the LCS is " << LCSLength(X, Y, X.length(), Y.length()); return 0; } |
Output:
The length of the LCS is 4
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
class Main { // Function to find the length of the longest common subsequence of // sequences `X[0…m-1]` and `Y[0…n-1]` public static int LCSLength(String X, String Y, int m, int n) { // return if the end of either sequence is reached if (m == 0 || n == 0) { return 0; } // if the last character of `X` and `Y` matches if (X.charAt(m - 1) == Y.charAt(n - 1)) { return LCSLength(X, Y, m - 1, n - 1) + 1; } // otherwise, if the last character of `X` and `Y` don't match return Integer.max(LCSLength(X, Y, m, n - 1), LCSLength(X, Y, m - 1, n)); } public static void main(String[] args) { String X = "ABCBDAB", Y = "BDCABA"; System.out.println("The length of the LCS is " + LCSLength(X, Y, X.length(), Y.length())); } } |
Output:
The length of the LCS is 4
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Function to find the length of the longest common subsequence of # sequences `X[0…m-1]` and `Y[0…n-1]` def LCSLength(X, Y, m, n): # return if the end of either sequence is reached if m == 0 or n == 0: return 0 # if the last character of `X` and `Y` matches if X[m - 1] == Y[n - 1]: return LCSLength(X, Y, m - 1, n - 1) + 1 # otherwise, if the last character of `X` and `Y` don't match return max(LCSLength(X, Y, m, n - 1), LCSLength(X, Y, m - 1, n)) if __name__ == '__main__': X = 'ABCBDAB' Y = 'BDCABA' print('The length of the LCS is', LCSLength(X, Y, len(X), len(Y))) |
Output:
The length of the LCS is 4
The worst-case time complexity of the above solution is O(2(m+n)) and occupies space in the call stack, where m
and n
are the length of the strings X
and Y
. 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 repeatedly rather than generating new subproblems.
Let’s consider the recursion tree for two sequences of length 6 and 8 whose LCS is 0.
As we can see, the same subproblems (highlighted in the same color) are getting computed repeatedly. 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 repeatedly. This method is demonstrated below in C++, Java, and Python:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include <iostream> #include <string> #include <unordered_map> using namespace std; // Function to find the length of the longest common subsequence of substring // `X[0…m-1]` and `Y[0…n-1]` int LCSLength(string X, string Y, int m, int n, auto &lookup) { // return if the end of either string is reached if (m == 0 || n == 0) { return 0; } // construct a unique map key from dynamic elements of the input string key = to_string(m) + "|" + to_string(n); // if the subproblem is seen for the first time, solve it and // store its result in a map if (lookup.find(key) == lookup.end()) { // if the last character of `X` and `Y` matches if (X[m - 1] == Y[n - 1]) { lookup[key] = LCSLength(X, Y, m - 1, n - 1, lookup) + 1; } else { // otherwise, if the last character of `X` and `Y` don't match lookup[key] = max(LCSLength(X, Y, m, n - 1, lookup), LCSLength(X, Y, m - 1, n, lookup)); } } // return the subproblem solution from the map return lookup[key]; } int main() { string X = "ABCBDAB", Y = "BDCABA"; // create a map to store solutions to subproblems unordered_map<string, int> lookup; cout << "The length of the LCS is " << LCSLength(X, Y, X.length(), Y.length(), lookup); return 0; } |
Output:
The length of the LCS is 4
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
import java.util.HashMap; import java.util.Map; class Main { // Function to find the length of the longest common subsequence of substring // `X[0…m-1]` and `Y[0…n-1]` public static int LCSLength(String X, String Y, int m, int n, Map<String, Integer> lookup) { // return if the end of either string is reached if (m == 0 || n == 0) { return 0; } // construct a unique map key from dynamic elements of the input String key = m + "|" + n; // if the subproblem is seen for the first time, solve it and // store its result in a map if (!lookup.containsKey(key)) { // if the last character of `X` and `Y` matches if (X.charAt(m - 1) == Y.charAt(n - 1)) { lookup.put(key, LCSLength(X, Y, m - 1, n - 1, lookup) + 1); } else { // otherwise, if the last character of `X` and `Y` don't match lookup.put(key, Integer.max(LCSLength(X, Y, m, n-1, lookup), LCSLength(X, Y, m - 1, n, lookup))); } } // return the subproblem solution from the map return lookup.get(key); } public static void main(String[] args) { String X = "ABCBDAB", Y = "BDCABA"; // create a map to store solutions to subproblems Map<String, Integer> lookup = new HashMap<>(); System.out.println("The length of the LCS is " + LCSLength(X, Y, X.length(), Y.length(), lookup)); } } |
Output:
The length of the LCS is 4
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# Function to find the length of the longest common subsequence of substring # `X[0…m-1]` and `Y[0…n-1]` def LCSLength(X, Y, m, n, lookup): # return if the end of either string is reached if m == 0 or n == 0: return 0 # construct a unique key from dynamic elements of the input key = (m, n) # if the subproblem is seen for the first time, solve it and # store its result in a dictionary if key not in lookup: # if the last character of `X` and `Y` matches if X[m - 1] == Y[n - 1]: lookup[key] = LCSLength(X, Y, m - 1, n - 1, lookup) + 1 else: # otherwise, if the last character of `X` and `Y` don't match lookup[key] = max(LCSLength(X, Y, m, n - 1, lookup), LCSLength(X, Y, m - 1, n, lookup)) # return the subproblem solution from the dictionary return lookup[key] if __name__ == '__main__': X = 'ABCBDAB' Y = 'BDCABA' # create a dictionary to store solutions to subproblems lookup = {} print('The length of the LCS is', LCSLength(X, Y, len(X), len(Y), lookup)) |
Output:
The length of the LCS is 4
The time complexity of the above top-down solution is O(m.n) and requires O(m.n) extra space, where m
and n
are the length of the strings X
and Y
. Note that we can also use an array instead of a map. Check implementation here.
The 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 a bottom-up manner. In the bottom-up approach, we calculate the smaller values of LCS(i, j)
first, then build larger values from them.
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 following table is generated by the function LCSLength()
, which shows the LCS’s length between prefixes of X
and Y
. The i'th
row and j'th
column show the LCS’s length of substring X[0…i-1]
and Y[0…j-1]
.
This is demonstrated below in C++, Java, and Python:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
#include <iostream> #include <string> using namespace std; // Function to find the length of the longest common subsequence of substring // `X[0…m-1]` and `Y[0…n-1]` int LCSLength(string X, string Y) { int m = X.length(), n = Y.length(); // lookup table stores solution to already computed subproblems; // i.e., `lookup[i][j]` stores the length of LCS of substring // `X[0…i-1]` and `Y[0…j-1]` int lookup[m + 1][n + 1]; // first column of the lookup table will be all 0s for (int i = 0; i <= m; i++) { lookup[i][0] = 0; } // first row of the lookup table will be all 0s for (int j = 0; j <= n; j++) { lookup[0][j] = 0; } // fill the lookup table in a bottom-up manner for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { // if the current character of `X` and `Y` matches if (X[i - 1] == Y[j - 1]) { lookup[i][j] = lookup[i - 1][j - 1] + 1; } // otherwise, if the current character of `X` and `Y` don't match else { lookup[i][j] = max(lookup[i - 1][j], lookup[i][j - 1]); } } } // LCS will be the last entry in the lookup table return lookup[m][n]; } int main() { string X = "XMJYAUZ", Y = "MZJAWXU"; cout << "The length of the LCS is " << LCSLength(X, Y); return 0; } |
Output:
The length of the LCS is 4
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
class Main { // Function to find the length of the longest common subsequence of substring // `X[0…m-1]` and `Y[0…n-1]` public static int LCSLength(String X, String Y) { int m = X.length(), n = Y.length(); // lookup table stores solution to already computed subproblems, // i.e., `T[i][j]` stores the length of LCS of substring // `X[0…i-1]` and `Y[0…j-1]` int[][] T = new int[m + 1][n + 1]; // fill the lookup table in a bottom-up manner for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { // if the current character of `X` and `Y` matches if (X.charAt(i - 1) == Y.charAt(j - 1)) { T[i][j] = T[i - 1][j - 1] + 1; } // otherwise, if the current character of `X` and `Y` don't match else { T[i][j] = Integer.max(T[i - 1][j], T[i][j - 1]); } } } // LCS will be the last entry in the lookup table return T[m][n]; } public static void main(String[] args) { String X = "XMJYAUZ", Y = "MZJAWXU"; System.out.println("The length of the LCS is " + LCSLength(X, Y)); } } |
Output:
The length of the LCS is 4
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Function to find the length of the longest common subsequence of substring # `X[0…m-1]` and `Y[0…n-1]` def LCSLength(X, Y): m = len(X) n = len(Y) # lookup table stores solution to already computed subproblems; # i.e., `T[i][j]` stores the length of LCS of substring # `X[0…i-1]` and `Y[0…j-1]` T = [[0 for x in range(n + 1)] for y in range(m + 1)] # fill the lookup table in a bottom-up manner for i in range(1, m + 1): for j in range(1, n + 1): # if the current character of `X` and `Y` matches if X[i - 1] == Y[j - 1]: T[i][j] = T[i - 1][j - 1] + 1 # otherwise, if the current character of `X` and `Y` don't match else: T[i][j] = max(T[i - 1][j], T[i][j - 1]) # LCS will be the last entry in the lookup table return T[m][n] if __name__ == '__main__': X = 'XMJYAUZ' Y = 'MZJAWXU' print('The length of the LCS is', LCSLength(X, Y)) |
Output:
The length of the LCS is 4
The time complexity of the above bottom-up solution is O(m.n) and requires O(m.n) extra space, where m
and n
are the length of the strings X
and Y
. The space complexity of the 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 the field of bioinformatics. It is also widely used by revision control systems such as Git.
Also See:
References: https://en.wikipedia.org/wiki/Longest_common_subsequence_problem
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)