Start learning free

LESSON 249 OF 314 · DYNAMIC PROGRAMMING

Longest Common Subsequence in TypeScript: 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

    TYPESCRIPT · DYNAMIC PROGRAMMING

    Longest Common Subsequence in TypeScript, explained

    Problem overview

    The method longestCommonSubsequence(text1: string, text2: string): number returns the length of the longest subsequence that both strings share. A subsequence is what remains after deleting some characters, possibly none, without reordering the rest. So "ace" is a subsequence of "abcde", but "aec" is not.

    For text1 = "abcde" and text2 = "ace" the answer is 3, because "ace" appears in both. For "abc" and "def" no character is shared, so the answer is 0. Only the length is returned, not the subsequence itself. Both strings have between 1 and 1000 lowercase letters, and the solution should run in O(n · m) time.

    Approach: solve it for every pair of prefixes

    Trying every subsequence of one string is hopeless: a string of 1000 characters has 2 to the power of 1000 subsequences. The way out is to solve smaller versions first. 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 to the whole problem is dp[n][m], where n and m are the string lengths.

    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. For every other cell, compare the last characters of the two prefixes, text1[i - 1] and text2[j - 1]:

    • They are equal. That character can end a common subsequence, so dp[i][j] = dp[i - 1][j - 1] + 1: the best answer for the two shorter prefixes, plus this shared character. Nothing does better, because removing the last character of 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. That makes dp[i][j] the larger of dp[i - 1][j] (without the last character of text1) and dp[i][j - 1] (without the last character of text2).

    Filling the table row by row, left to right, guarantees that the cells above, to the left and diagonally up-left are known when they are needed.

    Step by step

    1. Store the two lengths in const n = text1.length and const m = text2.length. They appear in the table size, the loop bounds and the answer.
    2. Create the table dp, typed number[][], with n + 1 rows of m + 1 zeros. Array.from({ length: n + 1 }, ...) calls the given function once per row, and each call returns a new new Array(m + 1).fill(0).
    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, inside the first loop.
    5. The equal case. If text1[i - 1] === text2[j - 1], set dp[i][j] = dp[i - 1][j - 1] + 1. The first i characters end at index i - 1, because strings count from 0 while the table counts characters.
    6. The different case. In the else branch, 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.

    For "abcde" and "ace" the finished table is below. Rows go with the prefixes of text1 (0 to 5 characters) and columns with the prefixes of text2 (0 to 3 characters):

    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 cell is 3, the answer. It grew along the diagonal: a matches at row 1, c at row 3 and e at row 5.

    The solution in TypeScript

    class Solution {
        longestCommonSubsequence(text1: string, text2: string): number {
            const n = text1.length;
            const m = text2.length;
            const dp: number[][] = 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];
        }
    }
    

    The TypeScript details worth knowing:

    • Why Array.from for the rows. new Array(n + 1).fill(new Array(m + 1).fill(0)) looks shorter but creates the inner array once and puts the same object in every slot. After setting bad[1][1] = 7 on a 3 by 3 table built that way, JSON.stringify(bad) is [[0,7,0],[0,7,0],[0,7,0]]: all rows changed together. Built with Array.from, the same assignment gives [[0,0,0],[0,7,0],[0,0,0]].
    • Indexing a string. text1[i - 1] gives a one-character string. Comparing two of them with === compares their contents. An index out of range gives undefined instead of an error, which is why a wrong bound can fail silently: "abc"[5] is undefined.
    • Types are erased. The number[][] annotation helps the compiler and the editor but disappears in the JavaScript. new Array(m + 1) by itself is an array of empty slots, and fill(0) is what makes them real zeros.
    • UTF-16 code units. This works for the lowercase letters in the constraints. A string indexes by UTF-16 code unit, so characters outside the basic range (such as many emoji) take two positions.

    Complexity

    Time: O(n · m). The table has (n + 1) × (m + 1) cells and each cell takes constant work, which for two 1000-character strings is about a million steps.

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

    Edge cases and common mistakes

    • No shared characters. "abc" and "def" return 0, the length of the empty common subsequence.
    • Identical strings. "abc" and "abc" return 3, the whole string.
    • Single characters. "a" and "a" return 1, and "a" and "b" return 0.
    • Mixing up prefix length and index. Using text1[i] instead of text1[i - 1] reads one character too far, and at i = n it reads undefined, which never equals a character.
    • Confusing subsequence with substring. A substring must be contiguous. For "abcde" and "ace" the longest common substring has length 1, while the longest common subsequence has length 3.
    • Taking only one neighbor when the characters differ. Both dp[i - 1][j] and dp[i][j - 1] have to be considered. Keeping only one can miss the longer answer.
    • Sharing rows between table slots. The fill trap above is the most common TypeScript-specific bug here.

    Testing

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