Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in Java: O(n · m) Table

Practice O(n · m) Read the full explanation

You are given two strings text1 and text2. Return the length of their longest common subsequence, or 0 if they have no common subsequence.

A subsequence of a string is what remains after deleting some of its characters, possibly none, without changing the order of the others. For example, "ace" is a subsequence of "abcde", but "aec" is not: the characters must keep their order. A common subsequence of two strings is a subsequence of both of them.

 

Example 1:

Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: "ace" is a subsequence of both strings. text2 has only 3 characters, so no common subsequence can be longer.

Example 2:

Input: text1 = "abcbdab", text2 = "bdcaba"
Output: 4
Explanation: "bcba" is a subsequence of both: b, c, b and a appear in this order in each string. "bdab" works too, and no common subsequence has 5 characters. Only the length is returned.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: No character appears in both strings, so the only common subsequence is the empty one.

 

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 are made of lowercase English letters only, a to z.

Note:

Your algorithm should run in O(n · m) time and space, where n is the length of text1 and m the length of text2.



Trying every subsequence is far too slow: a string of 1000 characters has 21000 of them. Solve smaller versions of the problem instead: let dp[i][j] be the length of the longest common subsequence of the first i characters of text1 and the first j characters of text2. The table has (n + 1) × (m + 1) entries. Row 0 and column 0 stand for an empty prefix, which has nothing in common with anything, so they stay 0. The answer is dp[n][m].

Fill the table row by row, so the entries above, to the left and diagonally up-left of dp[i][j] are already known. Look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1]:
  • When they are equal, dp[i][j] = dp[i - 1][j - 1] + 1. Adding this shared character to the best common subsequence of the two shorter prefixes reaches that length, and nothing does better: removing the last character of any common subsequence leaves a common subsequence of the two shorter prefixes.
  • When they differ, dp[i][j] is the larger of dp[i - 1][j] and dp[i][j - 1]. A common subsequence can't end with both of them, so it leaves out at least one, and then it is a common subsequence of the prefixes without that character.

The table has (n + 1) × (m + 1) entries, and each one takes a constant amount of work: O(n · m) time and O(n · m) space.
Each row reads only itself and the row above it, so two rows of m + 1 numbers are enough, which brings the space down to O(m). The lesson keeps the whole table, which is easier to follow.
STEP 1 OF 7
    Ctrl + Enter to check

    JAVA · DYNAMIC PROGRAMMING

    Longest Common Subsequence in Java, explained

    Problem overview

    The method longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence, or 0 when they share none. A subsequence is what remains after deleting some characters, possibly none, without reordering the rest. "ace" is a subsequence of "abcde", but "aec" is not. Both strings have 1 to 1000 lowercase letters.

    For text1 = "abcde" and text2 = "ace" the answer is 3. For "abcbdab" and "bdcaba" it is 4: "bcba" appears in both, and so does "bdab". Only the length is returned, so it doesn't matter which one you find.

    Approach: a table of prefixes

    A string of 1000 characters has 2^1000 subsequences, so checking each against the other string is hopeless. Instead, solve small versions of the problem. Let dp[i][j] be the length of the longest common subsequence of the first i characters of text1 and the first j characters of text2. The answer is dp[n][m], where n and m are the two lengths.

    An empty prefix has nothing in common with anything, so row 0 and column 0 stay 0. For every other cell, compare the last characters of the two prefixes, text1.charAt(i - 1) and text2.charAt(j - 1):

    • Equal. Adding the shared character to the best answer for the two shorter prefixes gives dp[i - 1][j - 1] + 1. Nothing does better, because removing the last character of any common subsequence leaves a common subsequence of the shorter prefixes.
    • Different. A common subsequence can't end with both characters, so it leaves out at least one of them. The answer is the larger of dp[i - 1][j] and dp[i][j - 1].

    Filling the table row by row, left to right, means the three neighbors above, to the left and diagonally up-left are always filled first. For "abcde" and "ace" the finished table is below, with rows for the prefixes of text1 and columns for the prefixes of text2:

    [0, 0, 0, 0]
    [0, 1, 1, 1]
    [0, 1, 1, 1]
    [0, 1, 2, 2]
    [0, 1, 2, 2]
    [0, 1, 2, 3]

    The bottom-right cell is 3, the answer. Read the table as a record of the best score so far: each cell either extends the diagonal by one, when the two characters match, or inherits the better of its two neighbors, so the numbers never decrease along a row or down a column. The table stores only lengths. It does not say which characters form the subsequence, which is all the problem asks for.

    Step by step

    1. Store the two lengths in n and m, using length(). They appear in the table size and in both loops.
    2. Create dp as new int[n + 1][m + 1]. The extra row and column stand for the empty prefix. Java fills a new int array with zeros, so the table needs no initialization.
    3. Loop i from 1 to n. Row 0 is the empty prefix and already holds zeros.
    4. Loop j from 1 to m inside it, covering every column.
    5. Handle equal characters. Compare text1.charAt(i - 1) with text2.charAt(j - 1). The first i characters end at index i - 1, since strings count from 0 and the table counts characters. If they match, set dp[i][j] = dp[i - 1][j - 1] + 1.
    6. Handle different characters in the else: take Math.max of the cell above and the cell to the left.
    7. Return dp[n][m], which covers both strings in full.

    The solution in Java

    class Solution {
        public int longestCommonSubsequence(String text1, String text2) {
            int n = text1.length();
            int m = text2.length();
            int[][] dp = new int[n + 1][m + 1];
            for (int i = 1; i <= n; i++) {
                for (int j = 1; j <= m; j++) {
                    if (text1.charAt(i - 1) == text2.charAt(j - 1)) {
                        dp[i][j] = dp[i - 1][j - 1] + 1;
                    } else {
                        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                    }
                }
            }
            return dp[n][m];
        }
    }
    

    Java details worth noticing:

    • charAt returns a char. Strings can't be indexed with brackets, so text1.charAt(i - 1) is the way to read a character. Comparing two char values with == compares their values, which is right here. Comparing two String objects with == would compare references, so whole strings need equals.
    • A two-dimensional array is an array of arrays. new int[n + 1][m + 1] creates n + 1 rows of m + 1 zeros each, and dp[i][j] reads row i, column j.
    • Index shift. The table index is one larger than the string index, which is why dp[i][j] pairs with charAt(i - 1) and charAt(j - 1).
    • Memory. For two strings of 1000 characters the table holds about a million ints, around 4 MB, which is fine.

    Complexity

    Time: O(n · m). The table has (n + 1) × (m + 1) cells, and each takes constant work.

    Space: O(n · m) for the table. Each row reads only itself and the row above, so two rows of m + 1 numbers would be enough and bring the space down to O(m). Keeping the whole table is easier to follow, and it is what this lesson does.

    Edge cases and common mistakes

    • No shared characters. "abc" and "def" never match, and every cell stays 0, so the method returns 0.
    • Identical strings. "abc" and "abc" return 3, and "a" with "a" returns 1.
    • Repeated characters. "aaa" and "a" return 1: the shorter string is the limit.
    • Off-by-one in charAt. Writing charAt(i) instead of charAt(i - 1) reads the wrong character and, at i = n, throws StringIndexOutOfBoundsException.
    • Table too small. A table of size [n][m] has no room for the empty prefix, and dp[n][m] throws ArrayIndexOutOfBoundsException.
    • Confusing subsequence with substring. A substring must be contiguous; a subsequence may skip characters. In the different-characters case the table carries the best answer forward across skipped characters, which a substring would not.

    Testing

    • "abcde", "ace" gives 3.
    • "abcbdab", "bdcaba" gives 4.
    • "abc", "def" gives 0.
    • "a", "a" gives 1.
    • "abc", "abc" gives 3.
    • "aaa", "a" gives 1.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free