Loading algorithms…

Loading visualizer…

Algorithms/Dynamic Programming/Longest Common Subsequence

Longest Common Subsequence

Find the longest subsequence common to two strings. Used in diff tools and bioinformatics.

Strings2D DPSequence Alignment
SPEED
2D DP MATRIX: dp[str1][str2]
Active
Match (+1)
Top/Left
LCS Path
SUBSEQUENCE RECONSTRUCTIONLength: 0
lcs.js
1function longestCommonSubsequence(str1, str2) {
2 const m = str1.length, n = str2.length;
3 const dp = Array(m + 1).fill(0).map(() => Array(n + 1).fill(0));
4 
5 for (let i = 1; i <= m; i++) {
6 for (let j = 1; j <= n; j++) {
7 if (str1[i - 1] === str2[j - 1]) {
8 dp[i][j] = 1 + dp[i - 1][j - 1]; // Match!
9 } else {
10 dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // Mismatch
11 }
12 }
13 }
14 
15 // Traceback to construct LCS
16 let i = m, j = n, lcs = [];
17 while (i > 0 && j > 0) {
18 if (str1[i - 1] === str2[j - 1]) {
19 lcs.unshift(str1[i - 1]);
20 i--; j--; // Move diagonal
21 } else if (dp[i - 1][j] >= dp[i][j - 1]) {
22 i--; // Move up
23 } else {
24 j--; // Move left
25 }
26 }
27 return { length: dp[m][n], lcs: lcs.join('') };
28}

About the Longest Common Subsequence algorithm

Find the longest subsequence common to two strings. Used in diff tools and bioinformatics.

Category
Dynamic Programming
Difficulty
Medium
Time complexity
O(m·n)
Space complexity
O(m·n)
←Previous Algorithm
0/1 Knapsack
Dynamic ProgrammingO(n·W)
Next Algorithm→
Coin Change
O(n·amount)Dynamic Programming