Longest Common Subsequence (LCS) finds the longest subsequence present in two sequence strings in the same relative order using Dynamic Programming.
Create (M+1) x (N+1) grid filled with 0s for base string empty prefixes.
dp[0][j] = 0, dp[i][0] = 0When A[i-1] == B[j-1] (e.g. 's' matches 's', 'o' matches 'o'), set dp[i][j] = 1 + dp[i-1][j-1].
Matches found: 'o', 'n', 'e'Trace back from dp[M][N] to extract matched characters 'one'.
Longest Common Subsequence: 'one' (Length = 3)Compare two DNA gene codes to find matching mutation sequences while ignoring unmapped intermediate genes.
500 steps (Linear)
O(N × W) Memoized Time
O(N × W) Cache Matrix
Memory growth rate as N expands.
Relative efficiency rating for large N.
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| LCS DP Matrix | O(M × N) | O(M × N) |
function lcs(text1, text2) {
const m = text1.length, n = text2.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 (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[m][n];
}Computes minimal file line additions and deletions.
Compares nucleotide and protein amino acid sequences.
Validate your conceptual understanding, operation mechanics, and core concepts of Lcs.
LCS forms the foundational core of version control diff engines like `git diff`!
Strings loaded. Click Compute LCS to build the dynamic programming grid and backtrack the sequence.