Skip to main content
Advanced ~15 min read

Longest Common Subsequence (LCS)

The classic 2-D dynamic programming table: what the two texts share, computed cell by cell.

Prerequisites: Dynamic Programming, Recursion Basics

A subsequence keeps relative order but allows gaps: "ace" is a subsequence of "abcde", "aec" is not. The Longest Common Subsequence of two strings is the longest string that is a subsequence of both, the shared skeleton of the two texts. It powers `git diff` (what did these two files keep in common?), DNA sequence alignment in bioinformatics, and file comparison in every diff tool.

Brute force is exponential, try all subsequences of one string against the other. DP collapses it by asking a smaller question: LCS of prefixes. Let dp[i][j] be the LCS length of the first i characters of text1 and the first j of text2. If the current last characters match, they extend the best of both prefixes without them: dp[i][j] = dp[i-1][j-1] + 1. If they don't match, at least one of the two characters is useless, but we don't know which, so take the better of dropping each: dp[i][j] = max(dp[i-1][j], dp[i][j-1]). The corner cell dp[m][n] is the answer.

The table and the reconstruction

lcs.js
function lcsTable(a, b) {
  const m = a.length, n = b.length;
  const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (a[i - 1] === b[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;             // match: extend diagonal
      } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // drop one char
      }
    }
  }
  return dp;                                         // dp[m][n] = LCS length
}

function lcsString(a, b) {                           // walk backwards to rebuild
  const dp = lcsTable(a, b);
  let i = a.length, j = b.length;
  const out = [];
  while (i > 0 && j > 0) {
    if (a[i - 1] === b[j - 1]) { out.push(a[i - 1]); i--; j--; }
    else if (dp[i - 1][j] >= dp[i][j - 1]) i--;
    else j--;
  }
  return out.reverse().join("");
}

lcsString("ABCBDAB", "BDCABA"); // "BCBA" or "BCAB"/"BDAB", length 4

Cost summary

Operation / caseCostNotes
Fill the tableO(m·n)m, n = the two lengths
Reconstruct subsequenceO(m + n)one backwards walk
Space-optimized lengthO(min(m, n))length only, reconstruction needs the full table (or Hirschberg's divide and conquer)

LCS is the gateway to edit distance, shortest common supersequence, and diff algorithms, they all fill a 2-D table with the same rhythm.

Practice

What is the length of the LCS of "ACE" and "ABCDE"?

Reveal explanation

"ACE" is itself a subsequence of "ABCDE", A(0), C(2), E(4) all appear in order, so the LCS is the whole of "ACE" with length 3.

Check your understanding

  1. 1.When text1[i-1] === text2[j-1], why must the match come from dp[i-1][j-1]?
  2. 2.What is the time complexity of LCS for two strings of length m and n?
  3. 3.Running `git diff` between two file versions is closest to which computation?

Finished reading?

Mark it complete to earn +50 XP. Progress stays in your browser.

Keep going