Problem overview
The method 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 of a string after deleting some characters (maybe none) without reordering the rest. "ace" is a subsequence of "abcde", but "aec" is not. A common subsequence is one that both strings contain. Both strings have 1 to 1000 lowercase letters, and the method must run in O(n · m) time, where n and m are the lengths.
For "abcde" and "ace" the answer is 3, because "ace" appears in both. For "abcbdab" and "bdcaba" it is 4: "bcba" and "bdab" both work, and the method returns only the length. For "abc" and "def" it is 0.
Approach: a table of prefixes
A string of 1000 characters has 2^1000 subsequences, so listing them is out of the question. Instead, solve smaller versions of the problem and reuse the answers. 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 to the whole problem is dp[n][m].
Row 0 and column 0 stand for an empty prefix, which has nothing in common with any string, so they stay 0. That's why the table has n + 1 rows and m + 1 columns.
To fill dp[i][j], look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1]:
- They are equal. Then
dp[i][j] = dp[i - 1][j - 1] + 1. The shared character extends the best answer for the two shorter prefixes by one, and 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 of them. Then it is 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 the table row by row, left to right, guarantees the cell above, the cell on the left and the cell diagonally up-left are known when you need them.
This is the table for text1 = "abcde" (the rows) and text2 = "ace" (the columns), printed by a real run:
[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
- Copy each string's bytes into an array.
chars1comes fromArray(text1.utf8)andchars2fromArray(text2.utf8), both withlet. An array can be read by position, and the strings hold only the letters a to z, one byte each, so comparing bytes compares letters. - Store the lengths in
nandm, withlet. They come up often. - Create the table
dpwithvar:n + 1rows, each a row ofm + 1zeros, usingrepeating:andcount:twice. - Loop over the rows with
iin1...n. Row 0 is already zeros. Write the closing brace right away. - Loop over the columns inside it with
jin1...m, and close that loop too. - Handle equal characters. If
chars1[i - 1] == chars2[j - 1], setdp[i][j]todp[i - 1][j - 1] + 1. The firsticharacters end at indexi - 1, because the array counts from 0 and the table counts characters. - Handle different characters in the
else: setdp[i][j]tomax(dp[i - 1][j], dp[i][j - 1]). - Return
dp[n][m]after the outer loop.
The solution in Swift
class Solution {
func longestCommonSubsequence(_ text1: String, _ text2: String) -> Int {
let chars1 = Array(text1.utf8)
let chars2 = Array(text2.utf8)
let n = chars1.count
let m = chars2.count
var dp = [[Int]](repeating: [Int](repeating: 0, count: m + 1), count: n + 1)
for i in 1...n {
for j in 1...m {
if chars1[i - 1] == chars2[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 Swift details worth a closer look:
- Strings can't be indexed by an integer.
text1[3]doesn't compile, because aStringis a sequence of characters of varying size. Converting once to an array lets the loops usechars1[i - 1]. utf8versus characters.text1.utf8is a view of the string's bytes, soArray(text1.utf8)is an array ofUInt8values. For lowercase English letters each byte is one letter. For text with accented letters the byte count and the character count differ:"héllo"has 5 characters but 6 bytes. The lesson's strings never contain such letters.Array(text1)would give an array ofCharactervalues, which is the safer choice for general text.- Comparing bytes.
chars1[i - 1] == chars2[j - 1]compares twoUInt8values with==. - Arrays are values.
[Int](repeating: 0, count: m + 1)is copied into each of then + 1rows, so writingdp[i][j]changes only that row. The rows are independent. - Closed ranges.
1...nincludesn. A closed range can't end below its start, but both strings have at least one character, so1...nand1...mare always valid. - Nested subscripts.
dp[i][j]reads rowiand then its columnj. Assigning through two subscripts works becausedpis avar.
Complexity
Time: O(n · m). The table has (n + 1) · (m + 1) entries and each one takes constant work.
Space: O(n · m). The method keeps the whole table. Each row reads only itself and the row above it, so two rows would be enough and would reduce the space to O(m). The lesson keeps the full table because it is easier to follow. For two strings of 1000 characters the table has about a million entries, which is fine.
Edge cases and common mistakes
- No shared letters.
"a"and"b"return 0. - Identical strings.
"abc"and"abc"return 3, the full length. - Repeated letters.
"aaaa"and"aa"return 2: the shorter string fits inside the longer one. - Same letters, opposite order.
"abc"and"cba"return 1. A common subsequence has to keep the order in both strings. - Off-by-one on indexes. The table row
irefers to characteri - 1of the array. Usingchars1[i]would read past the end on the last row and stop the program. - Confusing a subsequence with a substring. A substring must be contiguous.
"ace"is not a substring of"abcde", but it is a subsequence. - Big inputs. Two strings of 1000 characters are fine for this method. Trying every subsequence is not.
Testing
Results from running the reference solution:
"abcde","ace"gives3."abcbdab","bdcaba"gives4."abc","def"gives0."a","a"gives1."aaaa","aa"gives2."abc","cba"gives1.
