progress

~/problems / 2-D dynamic programming / String DP (edit distance, LCS)

Edit Distance

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write min_distance(word1: str, word2: str) -> int: the smallest number of single-character operations that turn word1 into word2. One operation is one of:

  • insert a character anywhere,
  • delete a character,
  • replace a character with a different one.

Examples:

  • min_distance("cart", "chart") == 1 (insert h)
  • min_distance("sunday", "saturday") == 3
  • min_distance("", "abc") == 3

Constraints: both words have at most 500 lowercase letters.

⭐ Bonus: a speed test with two 500-letter words earns a star in O(m·n) time. Trying every sequence of edits won't finish on it.

Show hint

let dp[i][j] be the answer for the first i letters of word1 and the first j letters of word2.

Topic: String DP (edit distance, LCS). dp[i][j] over prefixes of two strings; palindromes by expanding or by length.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc