V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Longest Common Subsequence

Fill for the optimal length, then trace for an actual subsequence

Preserve order without requiring adjacency

A subsequence keeps the original character order but may skip characters. For prefixes of strings X and Y, let dp[i][j] be their longest common subsequence length. Empty prefixes form the zero row and column.

Match diagonally or discard one character

When X[i - 1] === Y[j - 1], append that shared character to the best solution for the shorter prefixes, giving the top-left value plus 1. Otherwise one current character must be skipped, so keep the larger value from the up and left cells.

After the table is full, the player traces backward from the bottom-right cell. A character match moves diagonally and records that character; a mismatch follows a neighboring cell that preserves the optimal length. The highlighted path reconstructs ACD.

∅ACDF
∅00000
A0
B0
C0
D0

Initialize the empty-prefix row and column to 0.

1function lcs(x: string, y: string): string {
2 const m = x.length, n = y.length;
3 const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
4 for (let i = 1; i <= m; i++) {
5 for (let j = 1; j <= n; j++) {
6 if (x[i - 1] === y[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1; // equal: top-left + 1
7 else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // different: max of up/left
8 }
9 }
10 let i = m, j = n, s = "";
11 while (i > 0 && j > 0) { // reconstruct the LCS
12 if (x[i - 1] === y[j - 1]) { s = x[i - 1] + s; i--; j--; } // take the character and move diagonally
13 else if (dp[i - 1][j] >= dp[i][j - 1]) i--; // follow the larger up/left value
14 else j--;
15 }
16 return s;
17}
String XABCD
String YACDF
1 / 24

Value first, witness second

The table takes O(mn) time and space. This two-phase pattern appears throughout dynamic programming: first compute the optimal value, then follow stored choices to recover a concrete solution.

LCS underlies sequence comparison and diff tools. A common subsequence need not be contiguous, which distinguishes it from a common substring.

Contrast this maximum-length recurrence with Edit Distance, or continue to a one-dimensional subsequence DP in Longest Increasing Subsequence.