CodingNodes / 2-D Dynamic Programming / Edit Distance System design Space play · ←→ step · R restart

Problem

You are given two strings word1 and word2. In one step you may do any one of these:

  • insert a letter anywhere in the word,
  • delete a letter,
  • replace a letter with a different one.

Return the fewest steps needed to turn word1 into word2.

Constraints

  • 0 ≤ word1.length, word2.length ≤ 500
  • both words use lowercase English letters

Examples: pick one to animate

Solutions

TimeO(m · n) SpaceO(m · n)

Time: The table has (m + 1) · (n + 1) cells and each one is filled from three neighbours in constant time.

Space: The full table of (m + 1) · (n + 1) numbers is stored.

Let dp[i][j] be the fewest edits to turn the first i letters of word1 into the first j of word2. The first row and column are plain inserts and deletes. If the last letters match, copy the diagonal. Otherwise take one edit plus the best of the three neighbours: above (delete), left (insert) or diagonal (replace).