Problem overview
The function longest_common_subsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence. A subsequence keeps some characters of a string, possibly none, in their original order. A common subsequence is one that both strings contain.
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; only the length is returned). For "abc" and "def" it is 0.
Approach: a table of prefixes
Checking every subsequence of one string against the other is hopeless: a string of 1000 characters has 2^1000 subsequences. 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.
Look at the last characters of the two prefixes:
- 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, 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. Then
dp[i][j]is the larger ofdp[i - 1][j](drop the last character oftext1) anddp[i][j - 1](drop the last character oftext2).
An empty prefix has nothing in common with anything, so row 0 and column 0 stay 0. For "abcde" and "ace" the finished table is:
[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 last number, 3, is the answer. Rows are the prefixes of text1 (0 to 5 characters) and columns the prefixes of text2 (0 to 3).
Step by step
- Take the bytes of each string with
as_bytes(), intobytes1andbytes2. A RustStringcan't be indexed by position, but a byte slice can. The input contains only the letters a to z, one byte each, so comparing bytes compares letters. - Store the lengths in
nandm. They come up in the table size, the loops and the answer. - Create the table
dpwithn + 1rows ofm + 1zeros, usingvec!twice. The extra row and column are the empty prefixes. Writing0i32makes the entriesi32, the return type. - Loop over the rows with
for i in 1..=n. Row 0 already holds zeros, and rowncovers all oftext1. - Loop over the columns with
for j in 1..=m. Going row by row and left to right, the entries above, to the left and diagonally up-left ofdp[i][j]are already filled. - Handle equal characters. The first
icharacters end at byte indexi - 1, because bytes count from 0 while the table counts characters. Ifbytes1[i - 1] == bytes2[j - 1], setdp[i][j]todp[i - 1][j - 1] + 1. - Handle different characters in the
elsebranch withmax: the larger ofdp[i - 1][j]anddp[i][j - 1]. - Return
dp[n][m]with no semicolon.
The solution in Rust
impl Solution {
fn longest_common_subsequence(text1: String, text2: String) -> i32 {
let bytes1 = text1.as_bytes();
let bytes2 = text2.as_bytes();
let n = bytes1.len();
let m = bytes2.len();
let mut dp = vec![vec![0i32; m + 1]; n + 1];
for i in 1..=n {
for j in 1..=m {
if bytes1[i - 1] == bytes2[j - 1] {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = dp[i - 1][j].max(dp[i][j - 1]);
}
}
}
dp[n][m]
}
}
The Rust details worth a closer look:
- Strings and bytes. A
Stringholds UTF-8 text, and indexing it by position is not allowed because a character can take several bytes.as_bytes()borrows the same data as a&[u8]without copying. This works for the lesson because the input is lowercase ASCII. For text with other characters it would compare bytes, not characters:"héllo"is 6 bytes long but has 5 characters, and its second byte is 195. For general text, collectchars()into aVec<char>instead. - Nested
vec!.vec![row; n + 1]clonesrowfor every slot, so each row is its own vector. Changingdp[i][j]doesn't affect other rows. - Indexes are
usize.n,m,iandjare allusize, sodp[i - 1][j - 1]needs no casts. The subtractions are safe because both loops start at 1. maxis a method.a.max(b)returns the larger of twoi32values.- Borrowing.
bytes1andbytes2borrow fromtext1andtext2, which the function owns and which live until it returns.
Complexity
Let n and m be the lengths of text1 and text2.
Time: O(n · m). The table has (n + 1) × (m + 1) entries, and each takes constant work.
Space: O(n · m). The table is kept whole. Each row reads only itself and the row above, so two rows would be enough and cut the space to O(m), but the full table is easier to follow.
Edge cases and common mistakes
- No common characters.
"abc"and"def"give 0. The table never leaves zero. - Identical strings.
"abc"and"abc"give 3, and a repeated string such as 1000 lettersaagainst itself gives 1000. - Repeated letters.
"aaaa"and"aa"give 2: a common subsequence can't be longer than the shorter string. - Reversed order.
"abc"and"cba"give 1, and"ab"with"ba"gives 1: the same letters in a different order don't count. - Off-by-one on the index. The table cell
irefers to the character at byte indexi - 1. Comparingbytes1[i]would read past the end on the last row. - A subsequence is not a substring. The matching characters needn't be next to each other, which is why a mismatch takes the better of two neighbors instead of resetting to 0.
- Using the diagonal on a mismatch. Skipping a character from both strings at once is never better than skipping from one, because both of those cells are at least as large as the diagonal one.
Testing
"abcde","ace"gives3."abcbdab","bdcaba"gives4."abc","def"gives0."a","a"gives1."aaaa","aa"gives2."abc","cba"gives1.
