Skip to content

Visualizers

LCS Visualizer

Compute the Longest Common Subsequence using a 2D DP matrix.

native Client-side
Ready to compute.

Execution Log

LCS Length: -
LCS Sequence: -
Current Action:

Idle

Legend:

Uncomputed
Active Lookups
Match (Diagonal step)
Backtrack Path

Longest Common Subsequence (LCS)

The Longest Common Subsequence is a classic computer science problem. Given two sequences, find the length of the longest subsequence present in both. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguously.

Dynamic Programming Relation

For two strings $S_1$ and $S_2$:

  • If $S_1[i] == S_2[j]$: $DP[i][j] = DP[i-1][j-1] + 1$ (matching diagonal transition)
  • If $S_1[i] \neq S_2[j]$: $DP[i][j] = max(DP[i-1][j], DP[i][j-1])$ (lookup left and top values)

Implementation

function lcs(s1, s2) {
  const m = s1.length;
  const n = s2.length;
  const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
  
  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (s1[i - 1] === s2[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[m][n];
}