InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Edit Distance

medium Original β†—
Solving tips
  • Recognize Levenshtein distance on a (prefix of A, prefix of B) grid: dp[i][j] = edits to turn word1[:i] into word2[:j].
  • On a character match walk the diagonal for free (dp[i-1][j-1]); on a mismatch pay 1 + min of the three neighbors: diagonal=replace, dp[i-1][j]=delete, dp[i][j-1]=insert.
  • Seed the base row/column with dp[i][0]=i and dp[0][j]=j (converting to/from empty costs its length); target O(m*n) time, O(min(m,n)) space with two rows.
  • Pitfall: adding 1 on a match (it carries over unchanged) or mixing up which neighbor is insert vs delete.

Problem

Given two strings word1 and word2, return the minimum number of single-character edits needed to turn word1 into word2. The allowed edits are:

  • Insert a character
  • Delete a character
  • Replace a character

This minimum is the classic Levenshtein distance.

Examples

  • word1 = "horse", word2 = "ros" β†’ 3 β€” horse β†’ rorse (replace hβ†’r), rorse β†’ rose (delete r), rose β†’ ros (delete e).
  • word1 = "intention", word2 = "execution" β†’ 5 β€” five edits align the two words optimally.
  • word1 = "", word2 = "abc" β†’ 3 β€” three inserts build abc from nothing.

Constraints

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

With lengths up to 500 each, the expected solution is O(m Γ— n) β€” a grid of at most 250,000 cells.

Think about it first

Hint 1 Compare the two strings from one end. If the last characters match, they cost nothing β€” recurse on the two shorter prefixes. If they differ, you must pay 1 for one of insert / delete / replace and recurse on the correspondingly shortened strings.
Hint 2 The subproblem is "edit distance between `word1`'s first `i` characters and `word2`'s first `j` characters." Two indices β†’ a 2-D table `dp[i][j]`. Insert / delete / replace each move you to a different neighboring cell.
Hint 3 If `word1[i-1] == word2[j-1]`: `dp[i][j] = dp[i-1][j-1]`. Otherwise `dp[i][j] = 1 + min(dp[i-1][j-1]` (replace)`, dp[i][j-1]` (insert)`, dp[i-1][j]` (delete)`)`. Base row/column: converting to/from an empty string costs its length.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.