Delete Operation for Two Strings — LeetCode 583 Python Solution

MediumStringDynamic Programming
Problem
#583
Reading time
3 min

The problem

Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. In one step, you can delete exactly one character in either string.

Example

Input
word1 = "sea", word2 = "eat"
Output
2
Explanation
You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

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 i in range(1, m + 1):
            f[i][0] = i
        for j in range(1, n + 1):
            f[0][j] = j
        for i, a in enumerate(word1, 1):
            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]) + 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 583. Delete Operation for Two Strings 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

Frequently asked questions

How hard is LeetCode 583. Delete Operation for Two Strings?
LeetCode 583. Delete Operation for Two Strings is rated Medium on LeetCode.
What is the time complexity of LeetCode 583. Delete Operation for Two Strings?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 583. Delete Operation for Two Strings?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 583. Delete Operation for Two Strings cover?
LeetCode 583. Delete Operation for Two Strings 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