LeetCode 72 Edit Distance - Solution

The core idea

Define dp[i][j] = minimum edits to convert first i chars of word1 to first j chars of word2.

If word1[i-1] == word2[j-1]: characters match, no edit needed. dp[i][j] = dp[i-1][j-1].

Otherwise, take the minimum of:

  • Insert: dp[i][j-1] + 1
  • Delete: dp[i-1][j] + 1
  • Replace: dp[i-1][j-1] + 1

Base: dp[i][0] = i (delete all), dp[0][j] = j (insert all).