Given two strings word1 and word2, return the minimum number of operations (Insert, Delete, Replace) to convert word1 to word2.
"horse", "ros"3"abc", "abc"0Base: empty string needs length insertions/deletions. If chars match, copy diagonal. Else take min of insert (left+1), delete (up+1), replace (diag+1) — each operation costs 1.
Trying every sequence of edits explodes quickly. The same prefix pairs appear in many sequences.
Let dp of i and j be the edit distance between the first i characters of word one and the first j of word two. Turning a prefix into an empty string takes i deletions, so the first column is 0, 1, 2 and so on, and the first row likewise. If the characters match, no edit is needed, so copy the diagonal. Otherwise take 1 plus the smallest of three neighbours: above means delete, left means insert, and diagonal means replace. The bottom right cell is the answer.
Above is delete, left is insert, diagonal is replace. Matching characters are free.
Run the animation above on your own input, or watch the 1:55 video explanation of Edit Distance with a dry run and Java code.