Problem overview
The method longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence. A subsequence keeps some of a string's characters in their original order: "ace" is a subsequence of "abcde", but "aec" is not, because the order changed. The method returns only the length, and 0 when the strings share no characters.
For "abcde" and "ace" the answer is 3, because "ace" is a subsequence of both. For "abc" and "def" it is 0. Each string has between 1 and 1000 lowercase letters, and the lesson asks for O(n · m) time and space.
Approach: solve every pair of prefixes
A string of 1000 characters has 2^1000 subsequences, so comparing them all is impossible. Instead, solve smaller 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), with n and m the string lengths.
Look at the last character of each prefix, text1(i - 1) and text2(j - 1):
- They are equal. That shared character extends the best common subsequence of the two shorter prefixes, so
dp(i)(j) = dp(i - 1)(j - 1) + 1. Nothing does better: removing the last character from any common subsequence leaves a common subsequence of the shorter prefixes. - They differ. A common subsequence can't end with both characters, so it leaves out at least one. The result is the larger of
dp(i - 1)(j)(without the last character oftext1) anddp(i)(j - 1)(without the last character oftext2).
An empty prefix has nothing in common with anything, so row 0 and column 0 stay 0. That is why the table has n + 1 rows and m + 1 columns.
Step by step
- Store the lengths in two
vals,nfortext1.lengthandmfortext2.length. - Create the table with
Array.ofDim[Int](n + 1, m + 1). It makesn + 1rows ofm + 1zeros, which already covers the empty-prefix row and column. - Loop
iover1 to n. Row 0 is already filled, and the last row,n, stands for all oftext1. - Loop
jover1 to minside it. Going row by row and left to right, the entries above, to the left and diagonally up-left are always filled before they are needed. - If the last characters match (
text1(i - 1) == text2(j - 1)), setdp(i)(j)todp(i - 1)(j - 1) + 1. The firsticharacters end at indexi - 1, because the string counts from 0 while the table counts characters. - Otherwise set
dp(i)(j)tomath.max(dp(i - 1)(j), dp(i)(j - 1)). - End with
dp(n)(m), which covers both strings completely.
For "abcde" and "ace" the finished table has one row per prefix of text1, including the empty one:
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 entry, 3, is the answer. Each column corresponds to a prefix of "ace", from empty to the whole string.
The solution in Scala
class Solution {
def longestCommonSubsequence(text1: String, text2: String): Int = {
val n = text1.length
val m = text2.length
val dp = Array.ofDim[Int](n + 1, m + 1)
for (i <- 1 to n) {
for (j <- 1 to m) {
if (text1(i - 1) == text2(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))
}
}
}
dp(n)(m)
}
}
The Scala details worth a closer look:
Array.ofDim[Int](rows, cols). It builds an array of arrays and fills every cell with the defaultInt, 0. The cells are mutable, sodp(i)(j) = ...updates them even thoughdpis aval.- Two pairs of parentheses. Scala indexes each dimension with its own pair:
dp(i)(j), notdp[i][j]. - Indexing a string.
text1(i - 1)returns aChar, and==on twoChars compares their values. if/elseas a statement. Both branches assign todp(i)(j). The method's value is the last expression,dp(n)(m).
Complexity
Time: O(n · m). The table has (n + 1) × (m + 1) entries and each one takes a constant amount of work. For two strings of 1000 characters that is about a million entries.
Space: O(n · m), for the whole table. Each row reads only itself and the row above, so two rows would be enough to get O(m) space. The lesson keeps the whole table because it is easier to follow.
Edge cases and common mistakes
- Off-by-one on the strings. The table index
icounts characters, so the character at the end of the prefix istext1(i - 1). Usingtext1(i)reads one character too far and throws aStringIndexOutOfBoundsExceptionon the last row. - Table without the extra row and column. With only
nrows andmcolumns, the first characters need special cases. The zero row and column remove them. - Confusing subsequence with substring. A substring must be contiguous. For
"abcde"and"ace"the longest common substring has length 1, but the longest common subsequence has length 3. - No common characters.
"a"and"b", or"abc"and"def", leave the table all zeros and return 0. - Identical strings. The answer is the full length:
"abc"with"abc"gives 3. - Order of the arguments. The result is symmetric:
"abcde"with"aec"and"aec"with"abcde"both give 2.
Testing
"abcde"and"ace"give 3."abcbdab"and"bdcaba"give 4."abc"and"def"give 0."abc"and"abc"give 3."a"and"a"give 1."aaaa"and"aa"give 2."bl"and"yby"give 1.- Two strings of 1000
'a'characters give 1000.
