Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in JavaScript: O(n·m) DP Table

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

    JAVASCRIPT · DYNAMIC PROGRAMMING

    Longest Common Subsequence in JavaScript, explained

    Problem overview

    The method longestCommonSubsequence receives two strings, text1 and text2, and returns the length of their longest common subsequence, or 0 if they share none. A subsequence keeps some of a string's characters, possibly none, in their original order. "ace" is a subsequence of "abcde", but "aec" is not, because the order changed.

    For "abcde" and "ace" the answer is 3, since "ace" appears in both. For "abcbdab" and "bdcaba" it is 4 ("bcba" and "bdab" both work). For "abc" and "def" it is 0. Only the length is returned, not the subsequence. The lesson expects O(n · m) time and space, where n and m are the string lengths.

    Approach: a table of prefix answers

    Checking every subsequence of a 1000-character string is impossible, because there are 2^1000 of them. 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 final answer is dp[n][m].

    Row 0 and column 0 stand for an empty prefix, which has nothing in common with anything, so they 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]:

    • They are equal. Adding this shared character to the best answer for the two shorter prefixes gives 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 of them. The answer is the larger of dp[i - 1][j] (without the last character of text1) and dp[i][j - 1] (without the last character of text2).

    A quick check on "abcde" and "ace": the prefixes "abcd" and "ac" end in different characters, so their answer is the larger of the answers for "abc" with "ac" (2) and for "abcd" with "a" (1). Both are already in the table, and the entry becomes 2.

    Step by step

    1. Store the two lengths in const n and const m, since they are used many times.
    2. Build the table. Array.from({ length: n + 1 }, ...) calls its function once per row, and each call returns a new row, new Array(m + 1).fill(0), of zeros.
    3. Loop over the rows with i from 1 to n. Row 0 is the empty prefix and already holds zeros.
    4. Loop over the columns with j from 1 to m. Going row by row and left to right means the entries above, to the left and diagonally up-left are all filled before dp[i][j].
    5. Compare the last characters with ===. The first i characters end at index i - 1, hence text1[i - 1] and text2[j - 1]. When they match, set dp[i][j] to dp[i - 1][j - 1] + 1.
    6. Otherwise set dp[i][j] to Math.max(dp[i - 1][j], dp[i][j - 1]).
    7. Return dp[n][m], the answer for both whole strings.

    The solution in JavaScript

    class Solution {
        longestCommonSubsequence(text1, text2) {
            const n = text1.length;
            const m = text2.length;
            const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
            for (let i = 1; i <= n; i++) {
                for (let 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];
        }
    }
    

    Building a 2D array in JavaScript

    JavaScript has no built-in two-dimensional array, so the table is an array of arrays. The way you build it matters. This version looks shorter but is wrong:

    const dp = new Array(3).fill(new Array(3).fill(0));
    dp[1][1] = 7;
    console.log(JSON.stringify(dp)); // [[0,7,0],[0,7,0],[0,7,0]]
    

    fill puts the same row object into every slot, so changing one row changes them all. Array.from({ length: 3 }, () => new Array(3).fill(0)) runs the function once per row and creates three separate rows. With it, the same assignment prints [[0,0,0],[0,7,0],[0,0,0]].

    Strings can be indexed with brackets, so text1[i - 1] gives a one-character string, and === compares two such strings by content.

    The table for "abcde" and "ace"

    Rows are the prefixes of "abcde" (length 0 to 5) and columns the prefixes of "ace" (length 0 to 3):

    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. The 1 at row 1, column 1 appears because both prefixes end in a, and the diagonal entry above it is 0.

    Complexity

    The table has (n + 1) × (m + 1) entries, and each takes constant work, so the time is O(n · m) and the space is O(n · m). Each row reads only itself and the row above, so two rows would be enough, bringing the space down to O(m). The lesson keeps the whole table because it is easier to follow.

    Edge cases and common mistakes

    • No shared characters. "abc" and "def" never take the match branch, so the table stays 0 and the answer is 0.
    • Identical strings. "abc" with "abc" gives 3, the full length.
    • Off-by-one on the index. The table counts characters while the string counts from 0, so use text1[i - 1], not text1[i]. The latter would read past the end when i = n.
    • Sharing one row object. See the fill example above.
    • Confusing subsequence with substring. A substring must be contiguous, but a subsequence only has to keep the order. "ace" is not contiguous in "abcde" and still counts.

    Testing

    Results from the reference solution:

    "abcde", "ace"       -> 3
    "abcbdab", "bdcaba"  -> 4
    "abc", "def"         -> 0
    "a", "a"             -> 1
    "abc", "abc"         -> 3
    

    Two strings of 1000 a characters each give 1000, and the table has about a million entries, which is fine for O(n · m).

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free