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]anddp[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
- Store the two lengths in
nandm, usinglength(). They appear in the table size and in both loops. - Create
dpasnew int[n + 1][m + 1]. The extra row and column stand for the empty prefix. Java fills a newintarray with zeros, so the table needs no initialization. - Loop
ifrom 1 ton. Row 0 is the empty prefix and already holds zeros. - Loop
jfrom 1 tominside it, covering every column. - Handle equal characters. Compare
text1.charAt(i - 1)withtext2.charAt(j - 1). The firsticharacters end at indexi - 1, since strings count from 0 and the table counts characters. If they match, setdp[i][j] = dp[i - 1][j - 1] + 1. - Handle different characters in the
else: takeMath.maxof the cell above and the cell to the left. - 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:
charAtreturns achar. Strings can't be indexed with brackets, sotext1.charAt(i - 1)is the way to read a character. Comparing twocharvalues with==compares their values, which is right here. Comparing twoStringobjects with==would compare references, so whole strings needequals.- A two-dimensional array is an array of arrays.
new int[n + 1][m + 1]createsn + 1rows ofm + 1zeros each, anddp[i][j]reads rowi, columnj. - Index shift. The table index is one larger than the string index, which is why
dp[i][j]pairs withcharAt(i - 1)andcharAt(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. WritingcharAt(i)instead ofcharAt(i - 1)reads the wrong character and, ati = n, throwsStringIndexOutOfBoundsException. - Table too small. A table of size
[n][m]has no room for the empty prefix, anddp[n][m]throwsArrayIndexOutOfBoundsException. - 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"gives3."abcbdab","bdcaba"gives4."abc","def"gives0."a","a"gives1."abc","abc"gives3."aaa","a"gives1.
