Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in Rust: O(n · m) Dynamic Programming

Practice O(n · m) Read the full explanation

You are given two strings text1 and text2. Return the length of their longest common subsequence, or 0 if they have no common subsequence.

A subsequence of a string is what remains after deleting some of its characters, possibly none, without changing the order of the others. For example, "ace" is a subsequence of "abcde", but "aec" is not: the characters must keep their order. A common subsequence of two strings is a subsequence of both of them.

 

Example 1:

Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: "ace" is a subsequence of both strings. text2 has only 3 characters, so no common subsequence can be longer.

Example 2:

Input: text1 = "abcbdab", text2 = "bdcaba"
Output: 4
Explanation: "bcba" is a subsequence of both: b, c, b and a appear in this order in each string. "bdab" works too, and no common subsequence has 5 characters. Only the length is returned.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: No character appears in both strings, so the only common subsequence is the empty one.

 

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 are made of lowercase English letters only, a to z.

Note:

Your algorithm should run in O(n · m) time and space, where n is the length of text1 and m the length of text2.



Trying every subsequence is far too slow: a string of 1000 characters has 21000 of them. Solve smaller versions of the problem instead: 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 table has (n + 1) × (m + 1) entries. Row 0 and column 0 stand for an empty prefix, which has nothing in common with anything, so they stay 0. The answer is dp[n][m].

Fill the table row by row, so the entries above, to the left and diagonally up-left of dp[i][j] are already known. Look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1]:
  • When they are equal, dp[i][j] = dp[i - 1][j - 1] + 1. Adding this shared character to the best common subsequence of 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 two shorter prefixes.
  • When they differ, dp[i][j] is the larger of dp[i - 1][j] and dp[i][j - 1]. A common subsequence can't end with both of them, so it leaves out at least one, and then it is a common subsequence of the prefixes without that character.

The table has (n + 1) × (m + 1) entries, and each one takes a constant amount of work: O(n · m) time and O(n · m) space.
Each row reads only itself and the row above it, so two rows of m + 1 numbers are enough, which brings the space down to O(m). The lesson keeps the whole table, which is easier to follow.
STEP 1 OF 8
    Ctrl + Enter to check

    RUST · DYNAMIC PROGRAMMING

    Longest Common Subsequence in Rust, explained

    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 of dp[i - 1][j] (drop the last character of text1) and dp[i][j - 1] (drop the last character of text2).

    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

    1. Take the bytes of each string with as_bytes(), into bytes1 and bytes2. A Rust String can'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.
    2. Store the lengths in n and m. They come up in the table size, the loops and the answer.
    3. Create the table dp with n + 1 rows of m + 1 zeros, using vec! twice. The extra row and column are the empty prefixes. Writing 0i32 makes the entries i32, the return type.
    4. Loop over the rows with for i in 1..=n. Row 0 already holds zeros, and row n covers all of text1.
    5. 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 of dp[i][j] are already filled.
    6. Handle equal characters. The first i characters end at byte index i - 1, because bytes count from 0 while the table counts characters. If bytes1[i - 1] == bytes2[j - 1], set dp[i][j] to dp[i - 1][j - 1] + 1.
    7. Handle different characters in the else branch with max: the larger of dp[i - 1][j] and dp[i][j - 1].
    8. 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 String holds 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, collect chars() into a Vec<char> instead.
    • Nested vec!. vec![row; n + 1] clones row for every slot, so each row is its own vector. Changing dp[i][j] doesn't affect other rows.
    • Indexes are usize. n, m, i and j are all usize, so dp[i - 1][j - 1] needs no casts. The subtractions are safe because both loops start at 1.
    • max is a method. a.max(b) returns the larger of two i32 values.
    • Borrowing. bytes1 and bytes2 borrow from text1 and text2, 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 letters a against 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 i refers to the character at byte index i - 1. Comparing bytes1[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" gives 3.
    • "abcbdab", "bdcaba" gives 4.
    • "abc", "def" gives 0.
    • "a", "a" gives 1.
    • "aaaa", "aa" gives 2.
    • "abc", "cba" gives 1.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free