Delete Operation for Two Strings (LeetCode 583): Solution and Explanation

Medium
String
Dynamic Programming

You may delete one character at a time from either of two words. Find the fewest deletions that make the words identical.

Intuition

Whatever is left at the end is a string that appears, in order, inside both words: a common subsequence. Every other letter was deleted. So the fewest deletions come from keeping the longest common subsequence, and the answer is len(word1) + len(word2) - 2 * LCS.

You can also solve it head-on. Look at the last letters of two prefixes. If they are equal, keep both and the cost is whatever it took to equalise the shorter prefixes. If they differ, at least one of them has to go, so pay one deletion and take the cheaper of the two smaller problems.

Against an empty string there is no choice at all: every letter must be deleted. That gives the first row and column of the table.

Approach: 2D DP over prefixes

  1. Let dp[i][j] be the fewest deletions that make word1[:i] equal to word2[:j].
  2. Fill the borders: dp[i][0] = i and dp[0][j] = j.
  3. For each cell, if word1[i-1] == word2[j-1], set dp[i][j] = dp[i-1][j-1].
  4. Otherwise set dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1]): delete the word1 letter (come from above) or the word2 letter (come from the left).
  5. Return dp[m][n].

Step-by-step example

word1 = "sea", word2 = "eat"
  1. Borders: column 0 is 0,1,2,3 and row 0 is 0,1,2,3.
  2. Row 's': 's' matches none of 'e','a','t', so each cell is 1 + min(up, left), giving 2,3,4.
  3. Row 'e': 'e' matches 'e', so dp[2][1] = dp[1][0] = 1. Then dp[2][2] = 2 and dp[2][3] = 3.
  4. Row 'a': 'a' matches 'a', so dp[3][2] = dp[2][1] = 1. Then dp[3][3] = 1 + min(dp[2][3], dp[3][2]) = 2.
  5. The answer is dp[3][3] = 2: delete 's' from word1 and 't' from word2, leaving "ea" in both.

Code: Python, Java, C++

1class Solution:
2    def minDistance(self, word1: str, word2: str) -> int:
3        m, n = len(word1), len(word2)
4        dp = [[0] * (n + 1) for _ in range(m + 1)]
5        for i in range(m + 1):
6            dp[i][0] = i
7        for j in range(n + 1):
8            dp[0][j] = j
9        for i in range(1, m + 1):
10            for j in range(1, n + 1):
11                if word1[i - 1] == word2[j - 1]:
12                    dp[i][j] = dp[i - 1][j - 1]
13                else:
14                    dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1])
15        return dp[m][n]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each of the (m + 1) x (n + 1) cells is filled once in constant time.

Space

O(m * n)

The full table is stored. Each row only reads the row above, so two rows of length n + 1 are enough if memory matters.

Other approaches

Through the LCS (time O(m * n), space O(min(m, n)) with rolling rows)

Compute the length L of the longest common subsequence with the classic DP, then return m + n - 2L. Same table size, one extra formula.

Plain recursion (time O(2^(m+n)), space O(m + n))

Recurse on the last letters with the same rule but no memo. It re-solves the same prefix pairs many times and blows up exponentially.

Common mistakes

  • Forgetting the borders. dp[i][0] is i, not 0, because every letter of word1 must be deleted to match an empty word2.
  • Adding a substitution option as in Edit Distance. Here only deletions are allowed, so there is no 1 + dp[i-1][j-1] case.
  • Off-by-one on the letters. dp[i][j] talks about prefixes of length i and j, so the letters being compared are word1[i-1] and word2[j-1].
  • Counting deletions in only one word. Mismatched letters have to be removed from both words, which is why the LCS form subtracts 2L.

Frequently asked questions

How is this related to Longest Common Subsequence?

The letters that survive in both words form a common subsequence, and every other letter is deleted. Keeping the longest one minimises deletions, so the answer is m + n - 2 * LCS.

Why is it safe to keep both letters when they match?

If an optimal solution deleted one of two equal last letters, you could keep them both instead and pair them up without costing more deletions. So matching them is never worse.

How does it differ from Edit Distance?

Edit Distance also allows inserting and replacing a character, each costing one. Here the only move is deletion, so the recurrence drops the replace case.

Can I use less memory?

Yes. Each row depends only on the row above and the cell to its left, so a pair of one-dimensional arrays of length n + 1 is enough.