#72

Edit Distance

Medium 2D DP on two strings

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the minimum number of single-character inserts, deletes and replacements needed to turn word1 into word2.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: fewest inserts, deletes and replaces to turn one word into another.

Why this works: dp[i][j] for prefixes: same letter → no cost; otherwise 1 + the best of replace, delete or insert.

Example: "horse" → "ros"

horse → rorse (replace h) → rose (delete r) → ros (delete e) → 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting the base row/column, so converting to or from an empty string costs 0.

Solve on LeetCode ↗
Complexity
  • Time: O(n·m).
  • Space: O(n·m).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon