Top 150 Interview

Edit Distance

Detailed guide and Python implementation for the 'Edit Distance' problem.

問題提起

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

You have the following three operations permitted on a word:

1. Insert a character

2. Delete a character

3. Replace a character

Write a function minDistance(word1: str, word2: str) -> int.

制約
  • 0 <= len(word1), len(word2) <= 500
  • word1 and word2 consist of lowercase English letters

Example 1
Input
word1 = "horse", word2 = "ros"
Output
3
Explanation

horse -> rorse (replace 'h' with 'r') -> rose (remove 'r') -> ros (remove 'e').

Example 2
Input
word1 = "intention", word2 = "execution"
Output
5
Explanation

intention -> extention -> exention -> exection -> execution. Total 5 operations.

Need a Hint?
Consider using 2D DP-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。