Skip to content
AI360Xpert
Beta
Difficulty: Medium2-D Dynamic Programming

Edit Distance

Problem in Plain English

Given two words, find the fewest single-character insertions, deletions, or replacements that turn the first word into the second.

Problem Statement

Given two strings word1 and word2, return the minimum number of operations required to convert word1 into word2. The allowed operations are inserting a character, deleting a character, or replacing one character with another.

Each operation touches exactly one character position, and operations may be mixed freely: the classic conversion of "horse" into "ros" replaces h with r, then deletes the leftover r and e.

Return the smallest operation count over all possible conversion sequences.

Constraints

  • 0 <= word1.length, word2.length <= 500
  • word1 and word2 consist of lowercase English letters.

Examples

Example 1

Input
word1 = "horse", word2 = "ros"
Output
3

horse -> rorse replaces h with r, rorse -> rose deletes the second r, and rose -> ros deletes e: three operations. The complete prefix table also gives a lower bound of three, so this sequence is optimal.

Example 2

Input
word1 = "intention", word2 = "execution"
Output
5

intention -> inention deletes t, then enention, exention, and exection replace i with e and the two n letters with x and c; inserting u gives execution. These five edits attain the DP minimum.

Example 3

Input
word1 = "", word2 = "abc"
Output
3

There are no source characters to replace or delete. Insert a, then b, then c; one insertion creates at most one needed character, so fewer than three operations cannot work.

Intuition

An edit fixes a boundary of two unmatched strings. Insert consumes a needed target character, delete consumes an unwanted source character, and replace consumes one on both sides. Equal boundary characters can align for free. For horse -> ros, replacing h, deleting the later r, and deleting e costs three. Greedy replacement alone misses cheaper alignments, so compare all smaller prefix or suffix costs.

Approaches

Recursive Try All Ops

Solution Details

Reveal Recursive Try All Ops: intuition, complexity, and code

Hints

Hint 1
Use positions or prefix lengths instead of copying shorter strings on every call. What remains when either string becomes empty?
Hint 2
A mismatch has three possible alignment columns: insert, delete, replace. Which pointer does each advance?
Hint 3
Store minimum costs for prefix pairs; row-major filling makes the above, left, and diagonal dependencies available.
Hint 4
Equal characters can align at zero extra cost, but mismatches need the minimum of all three candidates, not a greedy replacement.

Edge Cases

  • Two empty words require 0 operations; a single empty word requires the other word length.
  • Identical words require no edits, including repeated-letter words.
  • Insertion and deletion both matter: "a" -> "aa" and "aa" -> "a" each cost 1.
  • Transposing letters is not one allowed operation: "ab" -> "ba" costs 2.
  • Completely disjoint length-500 strings require 500 replacements; the table stays practical while the recursive branching baseline does not.

Common Mistakes and Interview Tips

  • Charging for matching characters makes identical words have positive distance.
  • Initializing empty-prefix edges with zero makes necessary insertions and deletions free.
  • Confusing prefix lengths with character indices causes off-by-one errors; dp[i][j] compares word1[i-1] and word2[j-1].
  • In suffix recursion an insertion advances only target j; a deletion advances only source i. Reversing them changes the subproblem.
  • Python [[0]*(n+1)]*(m+1) aliases rows; updating one cell silently changes multiple prefixes.
  • Greedily replacing every mismatch can miss a cheaper insertion/deletion alignment, and a transposition is never a single edit here.
  • The published full grid uses O((m+1)(n+1)) allocation, including empty inputs; do not describe it as constant space or claim it reconstructs the actual edits.

Key Takeaway

Sequence transformation is an alignment problem. Define a state for each pair of prefix lengths, price empty prefixes honestly, and derive each transition from the last legal edit; memoizing these overlapping states removes exponential recomputation.