Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in Go: 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 9
    Ctrl + Enter to check

    GO · DYNAMIC PROGRAMMING

    Longest Common Subsequence in Go, explained

    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 of dp[i-1][j] and dp[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

    1. Store the lengths in n and m with :=. They come up often.
    2. Create dp as a slice of n+1 int slices with make([][]int, n+1). At this point the rows are still nil.
    3. Loop over dp with range, keeping only the index i.
    4. Give each row a new slice of m+1 ints with make. Every entry starts at 0, which is what row 0 and column 0 need.
    5. Loop over the rows with i from 1 to n. Row 0 is the empty prefix and is already done.
    6. Loop over the columns with j from 1 to m.
    7. If the last characters match, set dp[i][j] to dp[i-1][j-1] + 1.
    8. Otherwise set it to the larger of dp[i-1][j] and dp[i][j-1] with the built-in max.
    9. 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 are nil until each one gets its own make([]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 a byte, and len(text1) counts bytes. For lowercase English letters, one byte is one character, as the constraints promise. Comparing two byte values 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. make fills 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 i stands for the first i characters, so the last one is text1[i-1]. Writing text1[i] reads one character too far, and panics when i equals n.
    • 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 n by m has no place for the empty prefix, and dp[i-1][j-1] would reach index -1 for the first characters.

    Testing

    • "abcde", "ace" gives 3.
    • "abcbdab", "bdcaba" gives 4.
    • "abc", "def" gives 0.
    • "a", "a" gives 1.
    • "abc", "abc" gives 3.
    • "abc", "cba" gives 1.
    • "aaaa", "aa" gives 2.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free