☰ All problems

Edit Distance

A spell checker ranks its suggestions by edit distance: the fewest single-character edits that turn the misspelled word into a dictionary word. Each edit is one of:

  • inserting a character anywhere,
  • deleting a character,
  • replacing a character with a different one.

Given word1 and word2, return the minimum number of edits that transform word1 into word2. (This measure is also known as the Levenshtein distance.)

Example 1
Input: word1 = "recieve", word2 = "receive"
Output: 2

Explanation: Replace the i with e and the following e with i. The two letters are swapped, and no single edit fixes a swap.

Example 2
Input: word1 = "tommorow", word2 = "tomorrow"
Output: 2

Explanation: For example, delete the extra m and insert the missing r.

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

Explanation: Starting from an empty word, every character has to be inserted.

Constraints

  • Each word is between 0 and 500 characters long.
  • Both words use only 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