Skip to main content
60

Longest Common Subsequence

Mediumdynamic programmingstrings

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:2-D Dynamic ProgrammingRead the beginner guide

Given two strings text1 and text2, return the length of their longest common subsequence. If there is none, return 0.

Understand the problem

  • A subsequence keeps some characters in their original order, but not necessarily next to each other: "ace" is a subsequence of "abcde" (skip b and d). "aec" is not (wrong order).
  • A common subsequence is a subsequence of both strings.
  • You want the length of the longest one.

Example 1

text
Input:  text1 = "abcde", text2 = "ace"
Output: 3

"ace" is in both.

Example 2

text
Input:  text1 = "abc", text2 = "abc"
Output: 3

The whole string.

Example 3

text
Input:  text1 = "abc", text2 = "def"
Output: 0

No letters in common at all.

Constraints

  • 1 <= text1.length, text2.length <= 1000
  • Both strings contain lowercase English letters.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Compare the strings one character at a time: if the current characters match, count it and move both forward; if not, try skipping a character from either string and keep the better result, saving every answer in a 2-D table.

    The naive approach (and why it's slow)

    List every subsequence of text1 (there are 2^n of them) and check each against text2. With 1000 characters, that's impossible.

    The key insight: compare the first characters

    Let lcs[i][j] = the answer for the rest of the strings: text1 from position i, and text2 from position j. Look at the first character of each:

    • They match (text1[i] === text2[j]): use it! lcs[i][j] = 1 + lcs[i + 1][j + 1] (one letter, plus the best for the rest of both).
    • They differ: they can't both be matched here, so at least one of them is skipped. Try both options and keep the better one: lcs[i][j] = max(lcs[i + 1][j], lcs[i][j + 1]).
    • Base case: if either string is used up (i or j past the end), the answer is 0.
    text
    lcs[i][j] = 1 + lcs[i+1][j+1]                     if text1[i] === text2[j]
              = max(lcs[i+1][j], lcs[i][j+1])         otherwise

    This is a 2-D DP: the state is two positions, one in each string, so the saved answers form a grid.

    Step by step

    text1 = "abcde" (rows), text2 = "ace" (columns). The extra row and column marked · are the "string used up" base cases (all 0). Fill from the bottom-right corner up, so every cell you need (below, right, and diagonally down-right) is already filled:

    text
            a   c   e   ·
       a    3   2   1   0
       b    2   2   1   0
       c    2   2   1   0
       d    1   1   1   0
       e    1   1   1   0
       ·    0   0   0   0

    A few cells, explained:

    CellLettersRuleValue
    row e, col ematch1 + diagonal (0)1
    row c, col cmatch1 + diagonal (row d, col e = 1)2
    row b, col adiffermax(below = 2, right = 2)2
    row a, col amatch1 + diagonal (row b, col c = 2)3

    Answer: lcs[0][0] = 3.

    Saving memory: two rows

    Each row only uses the row below it (and itself). So the code keeps just two arrays: below (the finished row i + 1) and row (the one being filled). That's O(n) memory instead of O(m · n).

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With m and n the two string lengths:

    • Time: O(m · n). Each cell is computed once, in O(1).
    • Memory: O(n) with two rows (O(m · n) with the full table).

    Common mistakes

    • Confusing subsequence with substring. The letters don't need to be next to each other.
    • When the letters match, also trying the "skip" options. Not wrong, but unnecessary: using a match is never worse.
    • When they differ, adding 1. Only a match adds 1.
    • Off-by-one in the table size. It needs one extra row and column for the "used up" base cases.

    Going deeper

    • LCS is the core of diff tools (which lines stayed the same between two files) and DNA sequence comparison.
    • Edit Distance uses the same "match, or try each option" grid, with three options (insert, delete, replace) instead of two.
    • Don't confuse it with Longest Increasing Subsequence (1-D DP), which looks at a single sequence.

    Reference solution

    js
    /**
     * @param {string} text1
     * @param {string} text2
     * @return {number}
     */
    export default function longestCommonSubsequence(text1, text2) {
      // lcs[i][j] = answer for text1 from i and text2 from j. We keep only two rows:
      // `below` is the finished row i + 1. It starts as the "text1 used up" row: all 0.
      let below = new Array(text2.length + 1).fill(0)
      for (let i = text1.length - 1; i >= 0; i--) {
        // row i, with an extra 0 at the end for "text2 used up"
        const row = new Array(text2.length + 1).fill(0)
        for (let j = text2.length - 1; j >= 0; j--) {
          // Match: count it, plus the diagonal (rest of both strings).
          // Differ: skip text1[i] (below[j]) or skip text2[j] (row[j + 1]), whichever is better.
          row[j] = text1[i] === text2[j] ? 1 + below[j + 1] : Math.max(below[j], row[j + 1])
        }
        below = row // this row becomes the one below for the next i
      }
      return below[0] // lcs[0][0]: both strings from the start
    }
    ts
    export default function longestCommonSubsequence(text1: string, text2: string): number {
      // lcs[i][j] = answer for text1 from i and text2 from j. We keep only two rows:
      // `below` is the finished row i + 1. It starts as the "text1 used up" row: all 0.
      let below = new Array<number>(text2.length + 1).fill(0)
      for (let i = text1.length - 1; i >= 0; i--) {
        // row i, with an extra 0 at the end for "text2 used up"
        const row = new Array<number>(text2.length + 1).fill(0)
        for (let j = text2.length - 1; j >= 0; j--) {
          // Match: count it, plus the diagonal (rest of both strings).
          // Differ: skip text1[i] (below[j]) or skip text2[j] (row[j + 1]), whichever is better.
          row[j] = text1[i] === text2[j] ? 1 + below[j + 1] : Math.max(below[j], row[j + 1])
        }
        below = row // this row becomes the one below for the next i
      }
      return below[0] // lcs[0][0]: both strings from the start
    }
    python
    def longest_common_subsequence(text1: str, text2: str) -> int:
        # lcs[i][j] = answer for text1 from i and text2 from j. We keep only two rows:
        # `below` is the finished row i + 1. It starts as the "text1 used up" row: all 0.
        below = [0] * (len(text2) + 1)
        for i in range(len(text1) - 1, -1, -1):
            # row i, with an extra 0 at the end for "text2 used up"
            row = [0] * (len(text2) + 1)
            for j in range(len(text2) - 1, -1, -1):
                if text1[i] == text2[j]:
                    # Match: count it, plus the diagonal (rest of both strings).
                    row[j] = 1 + below[j + 1]
                else:
                    # Differ: skip text1[i] (below[j]) or skip text2[j] (row[j + 1]).
                    row[j] = max(below[j], row[j + 1])
            below = row  # this row becomes the one below for the next i
        return below[0]  # lcs[0][0]: both strings from the start