Longest Common Subsequence
Find how many letters two strings can share in the same order, by filling a table of answers for shorter pieces.
Given two strings text1text2
Example 1
Output: 3
Explanation: "ace" can be picked from both strings.
Example 2
Output: 3
Example 3
Output: 0
The Idea
If you have used a tool that compares two versions of a file, you have seen this problem at work. The tool looks for the lines that both versions keep, in the same order, and marks everything else as added or removed. Here the items are letters instead of lines.
Take Example 1. Cross out b and d from "abcde""ace""ace"
Order matters. The strings "abc""cba"
How do we find the longest one without listing them all? The string "abcde"
Look at the last letters instead. Both strings in Example 1 end with e, so match the two e's with each other. What is left to find is the longest common subsequence of "abcd""ac"
Now "abcd""ac""abc""ac""abcd""a"
Every step asks the same question about shorter beginnings of the two strings: "abcd""abcde""ac""ace"text1text2
The row labelled """"
The bottom-right cell, row e and column e, is the answer for the two whole strings: 3. Each cell was built from cells already filled, never worked out again from scratch. Building the answer for "abcde""ace"
Solution Approach
The table replaces a much slower search, and turning it into code means settling three things: what one entry holds, how it is filled from its neighbours, and where the filling starts. Keeping only two rows of the table is an optional way to save memory.
Trying every subsequence
Why not list every subsequence of text1text2text1text2text2
What one entry holds
What should a cell mean, exactly? The entry dp[i][j]text1text2dp[4][2]"abcd""ac"
Filling an entry from its neighbours
Which letters does dp[i][j]text1.charAt(i - 1)text2.charAt(j - 1)dp[i][j]dp[i - 1][j - 1] + 1
If they differ, dp[i][j]dp[i - 1][j]dp[i][j - 1]text1text2
Where the filling starts
Which cells can be written down straight away? Row 0 and column 0 pair a beginning with an empty one, and they share nothing, so they hold 0. A new Java int
Keeping only two rows
Can the table be smaller? Filling a row reads only that row and the one above it, so two rows are enough when only the length is wanted. Putting the shorter string along the columns makes the memory grow with the shorter string only. The full table has one use the two rows lose: walking back from the bottom-right cell through the matches, the orange cells in the picture, spells out a longest common subsequence itself, here a, c and e.
Java Solution
The method longestCommonSubsequence
- First, store the lengths of the two strings in
andm , and create the tablen withdp rows andm + 1 columns. Java fills it with zeros, which covers row 0 and column 0.n + 1 - Fill the rest with two loops, one inside the other. The outer loop moves
from 1 toi , one row at a time, and for eachm the inner loop movesi from 1 toj across the columns.n - Inside, compare
withtext1.charAt(i - 1) . Equal letters settext2.charAt(j - 1) todp[i][j] . Different letters set it to the larger ofdp[i - 1][j - 1] + 1 anddp[i - 1][j] , usingdp[i][j - 1] .Math.max - When both loops finish, the bottom-right cell
holds the answer for the two whole strings, and the method returns it.dp[m][n]
The main"abc""abc""cba""aggtab""gxtxayb"
public class LongestCommonSubsequence {
public static int longestCommonSubsequence(String text1, String text2) {
int m = text1.length();
int n = text2.length();
int[][] dp = new int[m + 1][n + 1]; // dp[i][j]: first i letters of text1, first j of text2
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1; // match the two last letters
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // drop one last letter
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
System.out.println(longestCommonSubsequence("abcde", "ace"));
System.out.println(longestCommonSubsequence("abc", "abc"));
System.out.println(longestCommonSubsequence("abc", "def"));
System.out.println(longestCommonSubsequence("", "abc"));
System.out.println(longestCommonSubsequence("abc", "cba"));
System.out.println(longestCommonSubsequence("aggtab", "gxtxayb"));
}
}
Running it prints:
3
3
0
0
1
4
The values 3, 3 and 0 at the top match Examples 1 to 3. The fourth line, 0, comes from the empty string: mdp[0][3]
The fifth line shows why order matters. The strings "abc""cba""gtab""aggtab""gxtxayb"
One change looks harmless but breaks the method. If different letters copied only the cell up and to the left, dp[i - 1][j - 1]"abcde""ace"
Complexity
The work is filling the table, one cell at a time.
- Time: O(m × n), because the two loops fill each of the m × n cells outside row 0 and column 0 once, with one letter comparison and one addition or
.Math.max - Space: O(m × n), because the table keeps (m + 1) × (n + 1) lengths, one for every pair of beginnings; keeping two rows brings it down to O(min(m, n)).
The same kind of table, with a different rule per cell, counts the edits that turn one word into another: see