Longest Common Subsequence
A common subsequence keeps letters that appear in both strings in the same order, with gaps allowed. Compare the last letters: if they match, they belong to the answer; if not, drop one of them and keep the better result. Fill those answers for every pair of prefixes, then walk back from the end to read the letters out.
Subsequence, Not Substring
A subsequence of a string keeps some of its letters in their original order and may skip any of the rest. ONE is a subsequence of STONE (skip S and T) and of LONGEST (skip L, G, S, T). The longest common subsequence (LCS) of two strings is the longest string that is a subsequence of both. For STONE and LONGEST it is ONE, length 3; no common subsequence of length 4 exists.
A substring must be contiguous. The longest common substring of the same pair is only 2 letters long: ST or ON. The two problems sound alike but have different answers and a slightly different recurrence, covered further down.
Why Matching Early Letters Fails
An obvious idea is to scan the first string and grab each letter as soon as it appears later in the second. On STONE and LONGEST that takes S (position 5 of LONGEST) and T (position 6). Now nothing in LONGEST is left after T, so O, N and E are lost and the result is ST, length 2 instead of 3. Taking S early used up the rest of the second string.
Trying every subsequence of the shorter string is correct but costs 2ⁿ checks: 32 for STONE, about a million for a 20-letter string, and over 10³⁰ for 100 letters. The choice at each letter, keep it or not, depends on choices further along, which is what dynamic programming handles.
The LCS Recurrence
- If i = 0 or j = 0, one prefix is empty: L(i, j) = 0
- If A[i] = B[j]: L(i, j) = L(i − 1, j − 1) + 1
- Otherwise: L(i, j) = max(L(i − 1, j), L(i, j − 1))
Let L(i, j) be the LCS length of the first i letters of A and the first j letters of B. The three rules above look only at the last letter of each prefix, A[i] and B[j].
- Equal letters are safe to pair: any LCS that does not end with them can be changed to end with them without getting shorter
- Different letters cannot both end the LCS, so at least one of them is unused and can be dropped
- The answer is L(m, n), with m and n the two lengths
Terms, operations, and practical uses
Key terms
- SubsequenceLetters kept in order with any gaps; ONE in STONE.
- SubstringA contiguous run of letters; ST in STONE.
- L(i, j)LCS length of the first i letters of A and the first j letters of B.
- TracebackThe backward walk through the grid that recovers the letters.
Related lessons and problems
- Two-Dimensional Dynamic ProgrammingFill order, borders and saving space for any two-index DP.
- Edit DistanceThe same grid with replace as a third move.
- Longest Increasing SubsequenceA one-string subsequence problem with an O(n log n) method.
- Dynamic ProgrammingStates, overlapping subproblems and the two ways to compute them.
- Longest Common Subsequence (problem)The standard interview version.
Code in Python, C++ and Java
def lcs_table(a, b):
t = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
t[i][j] = t[i - 1][j - 1] + 1
else:
t[i][j] = max(t[i - 1][j], t[i][j - 1])
return t
def lcs_string(a, b):
t = lcs_table(a, b)
i, j, out = len(a), len(b), []
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i, j = i - 1, j - 1
elif t[i - 1][j] >= t[i][j - 1]:
i -= 1
else:
j -= 1
return "".join(reversed(out))
def lcs_length_two_rows(a, b):
prev = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
cur[j] = prev[j - 1] + 1 if a[i - 1] == b[j - 1] else max(prev[j], cur[j - 1])
prev = cur
return prev[-1]
def greedy_match(a, b):
out, j = [], 0
for ch in a:
k = b.find(ch, j)
if k != -1:
out.append(ch)
j = k + 1
return "".join(out)
def longest_common_substring(a, b):
best, end = 0, 0
prev = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1] + 1
if cur[j] > best:
best, end = cur[j], i
prev = cur
return a[end - best:end]
def lcs3(a, b, c):
t = [[[0] * (len(c) + 1) for _ in range(len(b) + 1)] for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
for k in range(1, len(c) + 1):
if a[i - 1] == b[j - 1] == c[k - 1]:
t[i][j][k] = t[i - 1][j - 1][k - 1] + 1
else:
t[i][j][k] = max(t[i - 1][j][k], t[i][j - 1][k], t[i][j][k - 1])
return t[-1][-1][-1]
a, b = "STONE", "LONGEST"
print("table bottom row:", lcs_table(a, b)[-1])
print("length:", lcs_table(a, b)[-1][-1], "with two rows:", lcs_length_two_rows(a, b))
print("one longest common subsequence:", lcs_string(a, b))
print("greedy first-match:", greedy_match(a, b))
print("longest common substring:", longest_common_substring(a, b))
print("three strings with ONSET:", lcs3(a, b, "ONSET"))
print("empty string:", lcs_string("", b) == "")#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
using Table = vector<vector<int>>;
Table lcsTable(const string& a, const string& b) {
Table t(a.size() + 1, vector<int>(b.size() + 1, 0));
for (size_t i = 1; i <= a.size(); i++)
for (size_t j = 1; j <= b.size(); j++)
t[i][j] = a[i - 1] == b[j - 1] ? t[i - 1][j - 1] + 1 : max(t[i - 1][j], t[i][j - 1]);
return t;
}
string lcsString(const string& a, const string& b) {
Table t = lcsTable(a, b);
size_t i = a.size(), j = b.size();
string out;
while (i > 0 && j > 0) {
if (a[i - 1] == b[j - 1]) {
out += a[i - 1];
i--, j--;
} else if (t[i - 1][j] >= t[i][j - 1]) {
i--;
} else {
j--;
}
}
reverse(out.begin(), out.end());
return out;
}
int lcsLengthTwoRows(const string& a, const string& b) {
vector<int> prev(b.size() + 1, 0);
for (size_t i = 1; i <= a.size(); i++) {
vector<int> cur(b.size() + 1, 0);
for (size_t j = 1; j <= b.size(); j++)
cur[j] = a[i - 1] == b[j - 1] ? prev[j - 1] + 1 : max(prev[j], cur[j - 1]);
prev = cur;
}
return prev.back();
}
string greedyMatch(const string& a, const string& b) {
string out;
size_t j = 0;
for (char ch : a) {
size_t k = b.find(ch, j);
if (k != string::npos) {
out += ch;
j = k + 1;
}
}
return out;
}
string longestCommonSubstring(const string& a, const string& b) {
int best = 0, end = 0;
vector<int> prev(b.size() + 1, 0);
for (size_t i = 1; i <= a.size(); i++) {
vector<int> cur(b.size() + 1, 0);
for (size_t j = 1; j <= b.size(); j++)
if (a[i - 1] == b[j - 1]) {
cur[j] = prev[j - 1] + 1;
if (cur[j] > best) best = cur[j], end = i;
}
prev = cur;
}
return a.substr(end - best, best);
}
int lcs3(const string& a, const string& b, const string& c) {
vector<Table> t(a.size() + 1, Table(b.size() + 1, vector<int>(c.size() + 1, 0)));
for (size_t i = 1; i <= a.size(); i++)
for (size_t j = 1; j <= b.size(); j++)
for (size_t k = 1; k <= c.size(); k++)
t[i][j][k] = (a[i - 1] == b[j - 1] && b[j - 1] == c[k - 1])
? t[i - 1][j - 1][k - 1] + 1
: max({t[i - 1][j][k], t[i][j - 1][k], t[i][j][k - 1]});
return t[a.size()][b.size()][c.size()];
}
int main() {
string a = "STONE", b = "LONGEST";
Table t = lcsTable(a, b);
cout << "table bottom row: [";
for (size_t j = 0; j < t.back().size(); j++) cout << (j ? ", " : "") << t.back()[j];
cout << "]\n";
cout << "length: " << t.back().back() << " with two rows: " << lcsLengthTwoRows(a, b) << "\n";
cout << "one longest common subsequence: " << lcsString(a, b) << "\n";
cout << "greedy first-match: " << greedyMatch(a, b) << "\n";
cout << "longest common substring: " << longestCommonSubstring(a, b) << "\n";
cout << "three strings with ONSET: " << lcs3(a, b, "ONSET") << "\n";
cout << "empty string: " << (lcsString("", b).empty() ? "True" : "False") << "\n";
}import java.util.*;
public class Main {
static int[][] lcsTable(String a, String b) {
int[][] t = new int[a.length() + 1][b.length() + 1];
for (int i = 1; i <= a.length(); i++)
for (int j = 1; j <= b.length(); j++)
t[i][j] = a.charAt(i - 1) == b.charAt(j - 1) ? t[i - 1][j - 1] + 1 : Math.max(t[i - 1][j], t[i][j - 1]);
return t;
}
static String lcsString(String a, String b) {
int[][] t = lcsTable(a, b);
int i = a.length(), j = b.length();
StringBuilder out = new StringBuilder();
while (i > 0 && j > 0) {
if (a.charAt(i - 1) == b.charAt(j - 1)) {
out.append(a.charAt(i - 1));
i--;
j--;
} else if (t[i - 1][j] >= t[i][j - 1]) {
i--;
} else {
j--;
}
}
return out.reverse().toString();
}
static int lcsLengthTwoRows(String a, String b) {
int[] prev = new int[b.length() + 1];
for (int i = 1; i <= a.length(); i++) {
int[] cur = new int[b.length() + 1];
for (int j = 1; j <= b.length(); j++)
cur[j] = a.charAt(i - 1) == b.charAt(j - 1) ? prev[j - 1] + 1 : Math.max(prev[j], cur[j - 1]);
prev = cur;
}
return prev[b.length()];
}
static String greedyMatch(String a, String b) {
StringBuilder out = new StringBuilder();
int j = 0;
for (char ch : a.toCharArray()) {
int k = b.indexOf(ch, j);
if (k != -1) {
out.append(ch);
j = k + 1;
}
}
return out.toString();
}
static String longestCommonSubstring(String a, String b) {
int best = 0, end = 0;
int[] prev = new int[b.length() + 1];
for (int i = 1; i <= a.length(); i++) {
int[] cur = new int[b.length() + 1];
for (int j = 1; j <= b.length(); j++)
if (a.charAt(i - 1) == b.charAt(j - 1)) {
cur[j] = prev[j - 1] + 1;
if (cur[j] > best) {
best = cur[j];
end = i;
}
}
prev = cur;
}
return a.substring(end - best, end);
}
static int lcs3(String a, String b, String c) {
int[][][] t = new int[a.length() + 1][b.length() + 1][c.length() + 1];
for (int i = 1; i <= a.length(); i++)
for (int j = 1; j <= b.length(); j++)
for (int k = 1; k <= c.length(); k++)
t[i][j][k] = (a.charAt(i - 1) == b.charAt(j - 1) && b.charAt(j - 1) == c.charAt(k - 1))
? t[i - 1][j - 1][k - 1] + 1
: Math.max(t[i - 1][j][k], Math.max(t[i][j - 1][k], t[i][j][k - 1]));
return t[a.length()][b.length()][c.length()];
}
public static void main(String[] args) {
String a = "STONE", b = "LONGEST";
int[][] t = lcsTable(a, b);
System.out.println("table bottom row: " + Arrays.toString(t[a.length()]));
System.out.println("length: " + t[a.length()][b.length()] + " with two rows: " + lcsLengthTwoRows(a, b));
System.out.println("one longest common subsequence: " + lcsString(a, b));
System.out.println("greedy first-match: " + greedyMatch(a, b));
System.out.println("longest common substring: " + longestCommonSubstring(a, b));
System.out.println("three strings with ONSET: " + lcs3(a, b, "ONSET"));
System.out.println("empty string: " + (lcsString("", b).isEmpty() ? "True" : "False"));
}
}Step through it
Running on A = STONE, B = LONGEST
Filling the Grid
The lcs recurrence reads three neighbours: up-left, up and left. Store L in a grid with an extra row and column of zeros for the empty prefixes and fill it row by row, left to right; each cell is then ready when it is needed. The two-dimensional dynamic programming lesson covers fill orders and space in general.
For A = STONE (rows) and B = LONGEST (columns) the grid is 6 × 8. Rows S and T score only at the end of LONGEST, where S then T gives 2. Row O picks up a 1 from the O onward, row N a 2 from the N onward, and row E reaches 3 under the E, overtaking ST. The bottom row is 0, 0, 1, 2, 2, 3, 3, 3, and its last cell is the answer, 3.
How to Print the Longest Common Subsequence
- Start at i = m, j = n with an empty list
- If A[i] = B[j], add that letter to the list and move diagonally to (i − 1, j − 1)
- Otherwise move to the neighbour, up or left, that holds the larger value
- Stop when i or j reaches 0, then reverse the list
The length alone rarely helps; diff tools and DNA alignment need the letters. To print the longest common subsequence, keep the whole grid and walk backwards from the bottom-right cell, retracing which case produced each value.
- On the example the walk collects E, N, O, which reversed gives ONE
- When up and left are equal, either move is correct; preferring up or left can print a different LCS of the same length
- Listing every LCS can produce exponentially many strings, so programs usually print one
Matches as Lines That Do Not Cross
Write the two strings on two rows and draw a line between each pair of equal letters you use. A common subsequence is exactly a set of lines with no two crossing: crossing lines would need the letters in different orders in the two strings. The LCS is the largest such set. The diagram above shows the three lines O–O, N–N, E–E, and why adding S–S would cross them.
That is why Uncrossed Lines is the same problem with numbers instead of letters.
Variants Built on the Same Grid
Longest common substring. On a match the cell is the up-left value plus one; on a mismatch it resets to 0, because a gap breaks the run. The answer is the largest cell anywhere, not the bottom-right one. For STONE and LONGEST that is 2.
LCS of three strings. Add a third index: L(i, j, k) is up-left-back plus one when all three letters match, else the largest of the three ways to drop one letter. Time and memory become O(m × n × p). With ONSET as the third string the answer is still 3 (ONE). Taking the LCS of the first two and then intersecting with the third does not work in general, because the pairwise LCS you happened to keep may not be the one that suits the third string.
- Fewest deletions to make two strings equal: m + n − 2 × LCS
- Shortest common supersequence length: m + n − LCS
- Longest palindromic subsequence: the LCS of a string and its reverse
- Edit distance with inserts and deletes only (no replace): m + n − 2 × LCS; the full version is in edit distance
Cost and Memory
There are (m + 1)(n + 1) cells and each takes constant work, so the time is O(m × n). Keeping the grid for the traceback costs O(m × n) memory, about 100 MB for two 5,000-letter strings stored as 4-byte integers.
If only the length is needed, each row reads only the row above, so two rows of the shorter length are enough: O(min(m, n)) memory. Printing the letters in linear memory is possible with Hirschberg's divide-and-conquer method, which the edit distance lesson walks through.
- Empty string: LCS is empty, length 0
- Identical strings: the whole string
- No letter in common: length 0, and the walk adds nothing
Problems to Practise
Each of these is the LCS grid with a different question at the end.
- Longest Common Subsequence: the length
- Uncrossed Lines: the same grid on integers
- Delete Operation for Two Strings: m + n − 2 × LCS
- Longest Palindromic Subsequence: LCS with the reverse