Problem overview
The function longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence, or 0 if they share none. A subsequence is what remains after deleting some characters, possibly none, while keeping the others in order. "ace" is a subsequence of "abcde", but "aec" is not. A common subsequence is a subsequence of both strings. Both strings have 1 to 1000 lowercase letters.
For "abcde" and "ace" the answer is 3, because "ace" is in both. For "abcbdab" and "bdcaba" the answer is 4, and "bcba" and "bdab" both reach it. Only the length is returned. For "abc" and "def" the answer is 0.
Approach: solve every pair of prefixes
A string of 1000 characters has 2^1000 subsequences, so checking all of them 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], where n and m are the two lengths.
An empty prefix has nothing in common with any string, so row 0 and column 0 stay 0. That is why the table has n + 1 rows and m + 1 columns.
To fill dp[i][j], compare the last characters of the two prefixes, text1[i-1] and text2[j-1]. The prefix of length i ends at index i - 1, because a string counts from 0 while the table counts characters.
- They are equal. Then
dp[i][j] = dp[i-1][j-1] + 1. Adding the shared character to the best answer for 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 shorter prefixes. - They differ. A common subsequence can't end with both characters, so it leaves out at least one of them. It is then a common subsequence of the prefixes without that character, and
dp[i][j]is the larger ofdp[i-1][j]anddp[i][j-1].
Filling row by row, left to right, means the entries above, to the left and diagonally up-left are always ready. Here is the finished table for "abcde" and "ace", one printed row per prefix of text1 (the first row is the empty prefix):
[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 is 3, the answer.
Step by step
- Store the lengths in
nandmwith:=. They come up often. - Create
dpas a slice ofn+1int slices withmake([][]int, n+1). At this point the rows are stillnil. - Loop over
dpwithrange, keeping only the indexi. - Give each row a new slice of
m+1ints withmake. Every entry starts at 0, which is what row 0 and column 0 need. - Loop over the rows with
ifrom 1 ton. Row 0 is the empty prefix and is already done. - Loop over the columns with
jfrom 1 tom. - If the last characters match, set
dp[i][j]todp[i-1][j-1] + 1. - Otherwise set it to the larger of
dp[i-1][j]anddp[i][j-1]with the built-inmax. - Return
dp[n][m], which covers both whole strings.
The solution in Go
func longestCommonSubsequence(text1 string, text2 string) int {
n := len(text1)
m := len(text2)
dp := make([][]int, n+1)
for i := range dp {
dp[i] = make([]int, m+1)
}
for i := 1; i <= n; i++ {
for j := 1; j <= m; j++ {
if text1[i-1] == text2[j-1] {
dp[i][j] = dp[i-1][j-1] + 1
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
}
}
}
return dp[n][m]
}
The Go details worth a closer look:
- A two-dimensional slice is built in two steps.
make([][]int, n+1)creates only the outer slice, and its rows areniluntil each one gets its ownmake([]int, m+1). Without the loop,dp[i][j] = ...would panic with an index out of range. - Strings index by byte.
text1[i-1]is abyte, andlen(text1)counts bytes. For lowercase English letters, one byte is one character, as the constraints promise. Comparing twobytevalues with==needs no conversion. - The built-in
max. Since Go 1.21 it needs no import. The lessons use Go 1.22. - Zero values do the base cases.
makefills slices with zeros, so no code is needed for the empty-prefix row and column.
Complexity
Time: O(n · m). The table has (n + 1) × (m + 1) entries, and each takes a constant amount of work.
Space: O(n · m). The whole table is kept. Each row reads only itself and the row above, so two rows would be enough to bring the space down to O(m), but the full table is easier to follow.
Edge cases and common mistakes
- Off-by-one in the characters. The table index
istands for the firsticharacters, so the last one istext1[i-1]. Writingtext1[i]reads one character too far, and panics wheniequalsn. - Mixing up subsequence and substring. The common characters don't have to be next to each other. For
"abc"and"cba"the answer is 1, because any two of the letters appear in opposite orders. - No match at all.
"abc"and"def"leave the table full of zeros, and the function returns 0. - Repeated letters.
"aaaa"and"aa"give 2: the shorter string is a subsequence of the longer one. - Forgetting the extra row and column. A table of exactly
nbymhas no place for the empty prefix, anddp[i-1][j-1]would reach index-1for the first characters.
Testing
"abcde","ace"gives3."abcbdab","bdcaba"gives4."abc","def"gives0."a","a"gives1."abc","abc"gives3."abc","cba"gives1."aaaa","aa"gives2.
