All questions

Edit Distance

Premium

Edit Distance

The edit distance between two strings is the minimum number of single-character edits needed to turn one into the other, where each edit is an insert, a delete, or a replace and every edit costs 1. This is the classic Levenshtein distance (LeetCode 72): given word1 and word2, return the fewest operations that transform word1 into word2. It is the measure behind spell-checkers, fuzzy search, and DNA-sequence comparison — anywhere you need to score how far apart two strings are. See Levenshtein distance for background.

Signature

editDistance(word1, word2)   // two strings -> minimum edit count (a number)

Examples

editDistance('horse', 'ros');    // 3  (replace h→r, delete r, delete e)
editDistance('ab', 'abc');       // 1  (insert one character)
editDistance('', 'abc');         // 3  (insert every character)
editDistance('abcde', 'abcde');  // 0  (already identical)

Notes

  • Three operations — insert a character, delete a character, or replace one character with another. Each costs exactly 1; matching a character that is already correct costs nothing.
  • SymmetriceditDistance(a, b) always equals editDistance(b, a), because an insert in one direction is a delete in the other.
  • Empty string — the distance from '' to any string is that string's length (you insert every character), and the same the other way.
  • Result — always a non-negative integer; it is 0 only when the two strings are already identical. Comparison is case-sensitive, and you should build the function yourself without a library.

FAQ

What is the time and space complexity?
Filling the (m+1) x (n+1) table visits each cell once and does constant work per cell, so both time and space are O(m x n). The space can be reduced to O(min(m, n)) by keeping only the current and previous rows, since each cell depends only on the row above and the cell to its left.
How is edit distance different from Hamming distance?
Hamming distance only counts positions where two equal-length strings differ, so it allows replacements but not insertions or deletions. Edit distance (Levenshtein) allows all three operations and works on strings of different lengths, which is why it can align horse with ros.
Why is the table one row and one column bigger than the strings?
Row 0 and column 0 stand for the empty prefix of each string. They hold the base cases — turning an empty string into a j-character string takes j insertions, and reducing an i-character string to empty takes i deletions — which every interior cell builds on.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium