Top 150 InterviewMedium

Edit Distance

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

Problem Statement

Medium

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.

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

Examples

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

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.