Edit Distance — LeetCode 72 Python Solution

MediumStringDynamic Programming
Problem
#72
Reading time
3 min

The 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: Insert a character Delete a character Replace a character

This statement is abridged. Read the full problem on LeetCode.

Example

Input
word1 = "horse", word2 = "ros"
Output
3
Explanation
horse -> rorse (replace 'h' with 'r')

Python solution

Python
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m, n = len(word1), len(word2)
        f = [[0] * (n + 1) for _ in range(m + 1)]
        for j in range(1, n + 1):
            f[0][j] = j
        for i, a in enumerate(word1, 1):
            f[i][0] = i
            for j, b in enumerate(word2, 1):
                if a == b:
                    f[i][j] = f[i - 1][j - 1]
                else:
                    f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1
        return f[m][n]

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 72. Edit Distance is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150, LeetCode 75 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 72. Edit Distance?
LeetCode 72. Edit Distance is rated Medium on LeetCode.
What is the time complexity of LeetCode 72. Edit Distance?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 72. Edit Distance?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 72. Edit Distance cover?
LeetCode 72. Edit Distance is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview