☰ All problems

70. Edit Distance

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 anywhere,
  • delete a character,
  • replace a character with a different one.

(This number is also known as the Levenshtein distance.)

Example 1
Input: word1 = "kitten", word2 = "sitting"
Output: 3

Explanation: Replace k with s (sitten), replace e with i (sittin), then insert g at the end.

Example 2
Input: word1 = "flaw", word2 = "lawn"
Output: 2

Explanation: Delete the leading f, then append n.

Example 3
Input: word1 = "", word2 = "abc"
Output: 3

Explanation: Insert all three characters.

Constraints

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

Follow-up: If only insertions and deletions were allowed (no replace), how does the answer relate to the longest common subsequence?

💡 Hint 1

Work on prefixes: let dp[i][j] be the distance between the first i characters of word1 and the first j of word2. Turning a prefix into the empty string takes i deletions (and j insertions the other way).

💡 Hint 2

If the last characters match, dp[i][j] = dp[i-1][j-1]. Otherwise the last edit was a replace, a delete or an insert: 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]).

💡 Hint 3

Only the previous row is needed, so the table can be reduced to O(n) space.

/**
 * @param {string} word1
 * @param {string} word2
 * @return {number}
 */
function minDistance(word1, word2) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc