AlgoFrames

Edit distance in O(min(m, n)) space

Challenge · Write code · about 20 min

Return the fewest single-letter inserts, deletes and replacements that turn word1 into word2.

Use extra memory proportional to the shorter word: O(min(m, n)) for lengths m and n.

Example 1

Input:

["horse","ros"]

Output:

3

horse → rorse → rose → ros.

Example 2

Input:

["intention","execution"]

Output:

5

Constraints

  • 0 ≤ word1.length, word2.length ≤ 500
  • Both words use lowercase English letters

Learn the idea first: Space optimization: rolling rows and variables, a visual lesson.

More Space optimization: rolling rows and variables problems