InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Edit Distance

medium Original ↗ 00:00

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"3horse → 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug