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

Edit Distance

Levenshtein distance through a two-dimensional DP table

Count the cheapest string transformation

Edit distance is the minimum number of single-character insertions, deletions, and substitutions needed to transform one string into another. Define dp[i][j] as the cost of transforming the first i source characters into the first j target characters.

Each cell represents three possible edits

The first row counts insertions from an empty source, and the first column counts deletions to an empty target. If the current characters match, copy the top-left cell. Otherwise take 1 plus the minimum of top-left for substitution, up for deletion, and left for insertion.

The player transforms SAT into SUN. The amber cell is being solved, yellow cells supply candidate costs, and the new value turns green. The bottom-right cell is the answer for both complete strings.

∅SUN
∅0123
S1
A2
T3

Initialize the first row with insertion counts and the first column with deletion counts.

1function editDistance(a: string, b: string): number {
2 const m = a.length, n = b.length;
3 const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
4 for (let j = 0; j <= n; j++) dp[0][j] = j;
5 for (let i = 0; i <= m; i++) dp[i][0] = i;
6 for (let i = 1; i <= m; i++) {
7 for (let j = 1; j <= n; j++) {
8 if (a[i - 1] === b[j - 1]) {
9 dp[i][j] = dp[i - 1][j - 1];
10 } else {
11 dp[i][j] =
12 1 + Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]);
13 }
14 }
15 }
16 return dp[m][n];
17}
SourceSAT
TargetSUN
1 / 11

Complexity and reconstruction

Filling an (m + 1) x (n + 1) table costs O(mn) time and O(mn) space. If only the distance is needed, two rows reduce auxiliary space to O(n). Keeping the full table allows a backward trace of the actual edits.

Applications include spell checking, fuzzy search, text comparison, and biological sequence alignment.

Compare the three-neighbor minimum with the matching recurrence in Longest Common Subsequence.