Problem overview
The function longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence. A subsequence is what remains after deleting some characters, possibly none, while keeping the order of the rest. So "ace" is a subsequence of "abcde", but "aec" is not. A common subsequence is a subsequence of both strings, and the result is 0 when the strings share no character. Both strings have 1 to 1000 lowercase letters, and the statement asks for O(n * m) time and space, where n and m are the two lengths.
For "abcde" and "ace" the answer is 3: "ace" appears in both. For "abcbdab" and "bdcaba" it is 4. Both "bcba" and "bdab" have that length, and only the length is returned.
Approach: solve every pair of prefixes
A 1000-character string has 2^1000 subsequences, so comparing them all is out of the question. 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]. An empty prefix has nothing in common with anything, so row 0 and column 0 stay 0.
Look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1] (the first i characters end at index i - 1):
- They are equal. Then
dp[i][j] = dp[i - 1][j - 1] + 1. The shared character extends the best common subsequence of the two shorter prefixes. Nothing does better, because removing the last character from any common subsequence leaves a common subsequence of the shorter prefixes. - They differ. Then
dp[i][j]is the larger ofdp[i - 1][j]anddp[i][j - 1]. A common subsequence can't end with both different characters, so it leaves out at least one of them, and it is then a common subsequence of the prefixes without that character.
Filling the table row by row and left to right guarantees that the cells above, to the left and diagonally up-left are known when they are needed. This is the table for "abcde" and "ace", with one row per prefix of text1 (starting with the empty prefix) and one column per prefix 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 entry, 3, is the answer.
Step by step
- Store the lengths
text1.lengthandtext2.lengthinnandm, since they appear throughout. - Create the table with
Array(n + 1) { IntArray(m + 1) }. It has one more row and column than the strings have characters, to hold the empty prefixes. A newIntArraystarts with zeros, which is exactly the starting value row 0 and column 0 need. - Loop
iover1..n. Row 0 is the empty prefix and is already done. - Loop
jover1..minside it, for the same reason. - Handle equal last characters. If
text1[i - 1] == text2[j - 1], setdp[i][j]todp[i - 1][j - 1] + 1. - Handle different last characters in the
elsebranch:dp[i][j]ismaxOf(dp[i - 1][j], dp[i][j - 1]). - Return
dp[n][m], the answer for both whole strings.
The solution in Kotlin
class Solution {
fun longestCommonSubsequence(text1: String, text2: String): Int {
val n = text1.length
val m = text2.length
val dp = Array(n + 1) { IntArray(m + 1) }
for (i in 1..n) {
for (j in 1..m) {
if (text1[i - 1] == text2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1
} else {
dp[i][j] = maxOf(dp[i - 1][j], dp[i][j - 1])
}
}
}
return dp[n][m]
}
}
The Kotlin details worth a look:
- A table of rows.
Array(n + 1) { IntArray(m + 1) }is anArray<IntArray>. The lambda runs once for each row, so every row is a separate array. Reusing one pre-builtIntArrayfor all the rows would make them share the same storage, and writing to one row would change them all. Elements are read and written asdp[i][j]. - String indexing.
text1[i - 1]returns aChar, and==on twoCharvalues compares them by value. The index is zero-based, which is why the table'simaps to characteri - 1. 1..nis inclusive. It runs from 1 ton, the last row. The strings are never empty under the constraints, but for an empty string the range would be empty and the answer would stay 0.ifas a statement. Both branches assign todp[i][j]. The braces are optional for one-line branches but make the two cases easy to see.maxOfcomes from the standard library and needs no import.- Memory. A 1000 by 1000 problem needs a table of about a million
Intvalues, around 4 MB, which is comfortable.
Complexity
Time: O(n * m). The table has (n + 1) * (m + 1) entries, and each one takes constant work.
Space: O(n * m). The whole table is kept. Each row reads only itself and the row above, so two rows of m + 1 numbers would be enough for O(m) space, at the cost of a less direct picture of the table. The lesson keeps the full table.
Edge cases and common mistakes
- No common character.
"abc"and"def"give 0, and so do"a"and"b". - Identical strings.
"abc"and"abc"give 3, and"a"with"a"gives 1. - Same letters, different order.
"abc"and"cba"give 1: subsequences must keep their order. - Repeated letters.
"aaaa"and"aa"give 2, the length of the shorter string. - Off-by-one indexing. Writing
text1[i]instead oftext1[i - 1]compares the wrong characters and eventually reads past the end of the string, throwing aStringIndexOutOfBoundsExceptionwhenireachesn. - Confusing it with a substring. A common substring needs consecutive characters, and a subsequence doesn't. In the case of differing characters, a substring table would reset to 0, while here the larger neighbour is kept.
- Leaving out a case. Using only
dp[i - 1][j]in theelsebranch ignores the answers that skip a character oftext2instead.
Testing
These inputs give the following results from the reference solution:
"abcde"and"ace"give3."abcbdab"and"bdcaba"give4."abc"and"def"give0."abc"and"abc"give3."abc"and"cba"give1."aaaa"and"aa"give2.- Two strings of 1000 letters
agive1000.
