Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in C#: 2D Dynamic Programming, O(n · m)

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 7
    Ctrl + Enter to check

    C# · DYNAMIC PROGRAMMING

    Longest Common Subsequence in C#, explained

    Problem overview

    LongestCommonSubsequence receives two strings, text1 and text2, and returns the length of the longest sequence of characters that appears in both, in the same order but not necessarily side by side. It returns 0 if they share nothing.

    A subsequence is what's left after deleting some characters without reordering the rest. "ace" is a subsequence of "abcde"; "aec" is not. For "abcde" and "ace" the answer is 3. For "abcbdab" and "bdcaba" it is 4 ("bcba" and "bdab" both work), and for "abc" and "def" it is 0. Only the length is returned.

    Approach: solve for every pair of prefixes

    A string of 1000 characters has 2 to the power of 1000 subsequences, so comparing them all is out of the question. Solve smaller versions instead. Let dp[i, j] be the length of the longest common subsequence of the first i characters of text1 and the first j of text2. The answer is dp[n, m], where n and m are the lengths.

    Look at the last characters of the two prefixes, text1[i - 1] and text2[j - 1]:

    • Equal. Then dp[i, j] = dp[i - 1, j - 1] + 1. Add the shared character to the best answer for the two shorter prefixes. Nothing does better, because dropping the last character of any common subsequence leaves a common subsequence of the shorter prefixes.
    • Different. Then dp[i, j] is the larger of dp[i - 1, j] and dp[i, j - 1]. A common subsequence can't end with two different characters at once, so it leaves out at least one of them.

    An empty prefix has nothing in common with anything, so row 0 and column 0 stay 0. That is why the table has one more row and one more column than the strings have characters.

    Step by step

    1. Store the lengths text1.Length and text2.Length in n and m. Strings use Length, a property, with no parentheses.
    2. Create dp as new int[n + 1, m + 1], a rectangular two-dimensional array. It starts with zeros, which is exactly what row 0 and column 0 need.
    3. Loop i from 1 to n, row by row. Row 0 is already done.
    4. Loop j from 1 to m inside it. Row by row and left to right, the three neighbours dp[i - 1, j - 1], dp[i - 1, j] and dp[i, j - 1] are filled before dp[i, j].
    5. Equal characters. Compare text1[i - 1] and text2[j - 1]: the first i characters end at index i - 1, because strings count from 0 while the table counts characters. If equal, set dp[i, j] = dp[i - 1, j - 1] + 1.
    6. Different characters. In the else, set dp[i, j] to Math.Max(dp[i - 1, j], dp[i, j - 1]).
    7. Return dp[n, m].

    For "abcde" and "ace" the finished table, one row per prefix of text1 (from the empty one down to "abcde"), looks like this:

    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, 3, is the answer.

    Reading a bigger table

    For "abcbdab" and "bdcaba" the table has 8 rows and 7 columns:

    0 0 0 0 0 0 0
    0 0 0 0 1 1 1
    0 1 1 1 1 2 2
    0 1 1 2 2 2 2
    0 1 1 2 2 3 3
    0 1 2 2 2 3 3
    0 1 2 2 3 3 4
    0 1 2 2 3 4 4

    Row 2 stands for the prefix "ab", and the entry in its column 1 is 1: the last characters, 'b' and 'b', match, so it is dp[1, 0] + 1. In row 3 ("abc"), column 5 ("bdcab"), the last characters 'c' and 'b' differ, so the entry is the larger of the entry above it (2) and the entry to its left (1), which is 2. The last characters of the full strings, 'b' and 'a', differ, so the final entry takes the larger of two neighbours that are both 4. Each entry only ever looks at three earlier entries, which is why the table can be filled in one pass.

    The solution in C#

    class Solution {
        public int LongestCommonSubsequence(string text1, string text2) {
            int n = text1.Length;
            int m = text2.Length;
            int[,] dp = new int[n + 1, m + 1];
            for (int i = 1; i <= n; i++) {
                for (int 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] = Math.Max(dp[i - 1, j], dp[i, j - 1]);
                    }
                }
            }
            return dp[n, m];
        }
    }
    

    Details worth knowing:

    • int[,] versus int[][]. int[,] is a rectangular array indexed dp[i, j] with one pair of brackets. int[][] is an array of arrays that needs each row created separately and is indexed dp[i][j]. Writing dp[i][j] on an int[,] is a compile error.
    • Characters compare with ==. text1[i - 1] is a char, and == on two char values compares the characters themselves.
    • Zero-initialised. .NET sets every element of a new numeric array to 0, so the empty-prefix row and column need no code.

    Complexity

    Time: O(n · m). The table has (n + 1) × (m + 1) entries, and each takes constant work.

    Space: O(n · m) for the table. Each row reads only itself and the row above, so two rows of m + 1 numbers would be enough to bring the space down to O(m). The full table is easier to follow, and with strings up to 1000 characters it holds about a million ints.

    Edge cases and common mistakes

    • No common characters. "abc" and "def" give 0.
    • Identical strings. "abc" and "abc" give 3, and two strings of 1000 'a' characters give 1000.
    • Subsequence is not substring. "aab" and "azb" give 2, with "ab" as the common subsequence and its characters not adjacent in "azb".
    • Order matters. "aec" against "abcde" gives 2 ("ac" or "ae"), not 3.
    • Off-by-one on the characters. Using text1[i] instead of text1[i - 1] compares the wrong characters and reads past the end of the string on the last row.
    • Using only dp[i - 1, j - 1] when the characters differ. It throws away answers that skip just one of the two characters, so the result can come out too small.

    Testing

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