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

    The method longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence. A subsequence keeps some of a string's characters, in their original order, and drops the rest. "ace" is a subsequence of "abcde"; "aec" is not, because the order changed. Only the length is returned, and it is 0 when the strings share no characters.

    For "abcde" and "ace" the answer is 3. For "abcbdab" and "bdcaba" it is 4, and for "abc" and "def" it is 0. The strings have at most 1000 characters each, and the expected time is O(n · m).

    Approach: prefixes of both strings

    Checking every subsequence of a 1000-character string is hopeless, since there are 2^1000 of them. The fix is to 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 string lengths.

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

    • They are equal. That character extends the best answer for the two shorter prefixes: dp[i][j] = dp[i - 1][j - 1] + 1. Nothing does better, because removing the last character from any common subsequence leaves a common subsequence of the two shorter prefixes.
    • They differ. A common subsequence can't end with both characters, so it leaves out at least one. Then it fits the prefixes without that character, and the better of the two cases wins: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]).

    An empty prefix has nothing in common with anything, so row 0 and column 0 are all zeros. That is why the table has n + 1 rows and m + 1 columns.

    Step by step

    1. Store the lengths text1.size() and text2.size() in n and m. They come up often.
    2. Create the table dp as a vector<vector<int>> of n + 1 rows, each a vector of m + 1 zeros. The zeros cover the empty-prefix row and column.
    3. Loop over the rows i from 1 to n. Row 0 is already filled, and row n stands for all of text1.
    4. Loop over the columns j from 1 to m. Going row by row and left to right means the cells above, to the left and diagonally up-left are all filled before the current one.
    5. If the last characters match, compare text1[i - 1] with text2[j - 1]. The first i characters end at index i - 1, because the string counts from 0 while the table counts characters. On a match, set dp[i][j] to dp[i - 1][j - 1] + 1.
    6. Otherwise set dp[i][j] to the larger of dp[i - 1][j] and dp[i][j - 1].
    7. Return dp[n][m], the answer for both whole strings.

    The solution in C++

    class Solution {
    public:
        int longestCommonSubsequence(string text1, string text2) {
            int n = text1.size();
            int m = text2.size();
            vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
            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] = max(dp[i - 1][j], dp[i][j - 1]);
                    }
                }
            }
            return dp[n][m];
        }
    };
    

    For "abcde" and "ace" the finished table is below. Rows are the prefixes of "abcde" (from the empty one down to the whole string), and columns are the prefixes of "ace".

          ""  a  c  e
    ""     0  0  0  0
    a      0  1  1  1
    ab     0  1  1  1
    abc    0  1  2  2
    abcd   0  1  2  2
    abcde  0  1  2  3
    

    The bottom-right cell is 3, the answer.

    The C++ details:

    • The nested vector constructor. vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0)) makes n + 1 copies of a row of m + 1 zeros. Each row is its own vector, so changing one row doesn't touch the others.
    • int n = text1.size() converts the unsigned size to int. This is safe for lengths up to 1000, and it keeps i - 1 and j - 1 from wrapping around, as they would with unsigned counters.
    • The strings are taken by value. That copies them once, which costs O(n + m) and doesn't change the overall complexity. Taking them by const string& avoids the copies.
    • text1[i - 1] compares char values, which is exactly what is wanted for lowercase letters.

    Complexity

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

    Space: O(n · m) for the whole table. Each row reads only itself and the row above it, so two rows would be enough to bring the space down to O(m). The lesson keeps the full table because it is easier to follow.

    Edge cases and common mistakes

    • No shared characters. "abc" and "def" never hit the matching branch, so every cell stays 0 and the result is 0.
    • Identical strings. "abc" and "abc" return 3, the full length.
    • Reversed strings. "abc" and "cba" return 1: any single letter matches, but no two letters appear in the same order in both.
    • Repeated letters. "aab" and "azb" return 2 ("ab"). A letter in one string is matched at most once, because each match moves both prefixes back by one character.
    • Indexing with i instead of i - 1. Table row i stands for the first i characters, whose last one is text1[i - 1]. Reading text1[i] compares the wrong character, and on the last row it reaches one past the end of the string.
    • Substring versus subsequence. A subsequence need not be contiguous. For "abcde" and "ace" the answer is 3 even though "ace" is not a block inside "abcde".
    • Using dp[i - 1][j - 1] + 1 when characters differ. It counts a pair that doesn't match and gives answers that are too large.

    Testing

    • "abcde", "ace" gives 3.
    • "abcbdab", "bdcaba" gives 4.
    • "abc", "def" gives 0.
    • "abc", "abc" gives 3.
    • "abc", "cba" gives 1.
    • "a", "a" gives 1.
    • "aab", "azb" 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