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 text1 and text2, return the length of their longest common subsequence. That is the largest number of letters you can pick from each string so that both picks spell the same thing, in the same order. The picked letters do not have to sit next to each other. If the strings share no letter, return 0.

Example 1
Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: "ace" can be picked from both strings.
Example 2
Input: text1 = "abc", text2 = "abc"
Output: 3
Example 3
Input: text1 = "abc", text2 = "def"
Output: 0
Solution

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" and you are left with "ace", which is the whole of the second string. Letters picked from a string in their original order, with gaps allowed, form a subsequence. So "ace" is a subsequence of both strings, a common subsequence, and no common one is longer, so the answer is 3.

Order matters. The strings "abc" and "cba" hold the same three letters, but every two of them come in opposite orders in the two strings. Their longest common subsequence has just one letter.

How do we find the longest one without listing them all? The string "abcde" alone has 32 subsequences, counting the empty one, and each extra letter doubles that count.

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" and "ac", and the answer is that length plus 1 for the e.

Now "abcd" and "ac" end with different letters, d and c. A common subsequence cannot end with both of them, so at least one of the two is not used. Dropping d leaves "abc" against "ac", and dropping c leaves "abcd" against "a". The answer is the larger of those two.

Every step asks the same question about shorter beginnings of the two strings: "abcd" is the first four letters of "abcde", and "ac" the first two of "ace". So write the answer for each pair of beginnings into a table, with one row per beginning of text1 and one column per beginning of text2. Look at the picture below.

The table for text1 = abcde (rows) and text2 = ace (columns). Row "" and column "" hold 0. Orange cells, where the letters match, are the cell up and to the left plus 1. Cells where the letters differ, two of them teal, take the larger of the cell above and the cell to the left. The bottom-right cell holds 3.

The row labelled "" and the column labelled "" stand for the empty beginning, with no letters at all, so they hold 0. In the orange cells the letters match: row c, column c holds 2, one more than the 1 up and to its left. The two teal cells show what happens where the letters differ, and the white cells follow the same rule: row d, column c copies the 2 above it, which is larger than the 1 on its left.

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" and "ace" from stored answers for their shorter beginnings like this is called dynamic programming.

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 text1 and check each one against text2? Say text1 has m letters and text2 has n. Each of the m letters is either kept or crossed out, which gives 2m subsequences. Checking one against text2 takes a pass over its n letters, so the search costs about 2m × n steps. Thirty letters already give more than a billion subsequences.

What one entry holds

What should a cell mean, exactly? The entry dp[i][j] is the length of the longest common subsequence of the first i letters of text1 and the first j letters of text2. The table has m + 1 rows and n + 1 columns, so i and j can also be 0, the empty beginning. In the picture, dp[4][2] is row d, column c: "abcd" against "ac", which is 2.

Filling an entry from its neighbours

Which letters does dp[i][j] compare? The last letters of the two beginnings, text1.charAt(i - 1) and text2.charAt(j - 1), because positions in a Java string start at 0. If they are equal, dp[i][j] is dp[i - 1][j - 1] + 1, the cell up and to the left plus 1. Matching them never loses anything: a longest common subsequence that skips one of them can end with this pair instead and stay just as long.

If they differ, dp[i][j] is the larger of dp[i - 1][j] and dp[i][j - 1]. The cell above is the answer without the last letter of text1, and the cell to the left is the answer without the last letter of text2.

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 array is already full of zeros, so they need no code. Every other cell reads the cell above, the cell to the left and the cell up and to the left. Filling row by row, each row from left to right, always finds those three ready.

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 works in these steps:

  1. First, store the lengths of the two strings in m and n, and create the table dp with m + 1 rows and n + 1 columns. Java fills it with zeros, which covers row 0 and column 0.
  2. Fill the rest with two loops, one inside the other. The outer loop moves i from 1 to m, one row at a time, and for each i the inner loop moves j from 1 to n across the columns.
  3. Inside, compare text1.charAt(i - 1) with text2.charAt(j - 1). Equal letters set dp[i][j] to dp[i - 1][j - 1] + 1. Different letters set it to the larger of dp[i - 1][j] and dp[i][j - 1], using Math.max.
  4. When both loops finish, the bottom-right cell dp[m][n] holds the answer for the two whole strings, and the method returns it.

The main method runs the three examples, then an empty string against "abc", the same letters in opposite orders ("abc" and "cba"), and a longer pair, "aggtab" and "gxtxayb".

Java
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:

Output
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: m is 0, so the outer loop never starts and the method returns the 0 in dp[0][3].

The fifth line shows why order matters. The strings "abc" and "cba" share all three letters, yet the answer is 1, because any two of the letters come in opposite orders in the two strings. The last line, 4, is "gtab", which can be picked from both "aggtab" and "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], each step would drop the last letter of both strings at once. Run that way, "abcde" and "ace" give 1 instead of 3. Each cell then builds only on cells along one slanted line of the table, and in the picture no such line passes through two of the orange cells.

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 Edit Distance.