LeetCode #583 Medium

Delete Operation for Two Strings

Delete Operation for Two Strings is LeetCode 583 (Medium). You get two lowercase words, word1 and word2. One step deletes exactly one character from either word. Return the fewest steps that make the two words equal.

  • Deleting is the only move: no inserting and no replacing.
  • Each word has at most 500 letters, so a table with one cell per pair of positions (about 250,000 cells) is fast enough.
Constraints
  • 1 <= word1.length, word2.length <= 500
  • word1 and word2 consist of only lowercase English letters.
dynamic-programmingstringslcs
Open on LeetCode ↗
02

Intuition

Stop thinking about what to delete and look at what is left. After the deletions both words are the same string, and it was made by keeping some letters of word1 in order and some letters of word2 in order. So what is left is a common subsequence of the two words.

Fewer deletions means more letters kept, so keep the longest common subsequence (LCS). Its letters survive in both words, and every other letter goes.

So the minimum deletions to make two strings equal is m + n − 2 × LCS: the kept letters stay once in each word, so their count comes off both lengths.

How to spot this pattern

Two strings, one allowed edit, and a question about making them match. When the only edit is deleting, the letters that survive form a common subsequence, so the problem is a longest common subsequence in disguise.

03

Approach

Try it first

Before reading on, find the longest string you can get from both sea and eat by crossing out letters, then count how many letters you crossed out in total. Aim for O(m · n) time.

1

Let each cell stand for two prefixes

dp[i][j] is the LCS length of the first i letters of word1 and the first j letters of word2. Row 0 and column 0 stay 0, because an empty prefix shares nothing. That extra row and column let every cell read its neighbours without bounds checks.

2

When the last letters match, keep them

If word1[i - 1] == word2[j - 1], set dp[i][j] = dp[i - 1][j - 1] + 1. Pairing these two letters never hurts: a common subsequence that leaves one of them out can use this pair for its last letter instead and stay just as long.

3

When they differ, drop one of them

Two different letters cannot both end the common subsequence, so at least one of them is not in it. Drop either one and keep the better result: dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]).

4

Turn the LCS into a deletion count

Fill the table row by row, so the cells above, to the left and up-left are always ready. dp[m][n] is the LCS length L. word1 loses its other m − L letters and word2 its other n − L, so return m + n - 2 * L.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def minDistance(self, word1, word2):
▶3 m, n = len(word1), len(word2)
▶4 dp = [[0] * (n + 1) for _ in range(m + 1)]
▶5 for i in range(1, m + 1):
▶6 for j in range(1, n + 1):
▶7 if word1[i - 1] == word2[j - 1]:
▶8 dp[i][j] = dp[i - 1][j - 1] + 1
▶9 else:
▶10 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
▶11 return m + n - 2 * dp[m][n]
LCS length of each pair of prefixesemptyeatemptysea0000000word1seaword2eatempty prefixes share nothing → row and column 0 are 0
word1sea
word2eat
Each cell will hold the length of the longest common subsequence of a prefix of word1 (its row) and a prefix of word2 (its column). An empty prefix has nothing in common with anything, so the first row and column start at 0, which lets every other cell read its neighbours safely.
LCS length of each pair of prefixesemptyeatemptysea00000000word1seaword2eatletters differ0upor0left→0s differs from e → keep the larger: 0
letterss and e
up0
left0
cell0
s and e differ, so they cannot both end the common subsequence; one of them is left out. Dropping s gives the cell above (0), dropping e gives the cell to the left (0), and the larger, 0, is kept.
LCS length of each pair of prefixesemptyeatemptysea000000000word1seaword2eatletters differ0upor0left→0s differs from a → keep the larger: 0
letterss and a
up0
left0
cell0
s and a differ, so they cannot both end the common subsequence; one of them is left out. Dropping s gives the cell above (0), dropping a gives the cell to the left (0), and the larger, 0, is kept.
LCS length of each pair of prefixesemptyeatemptysea0000000000word1seaword2eatletters differ0upor0left→0s differs from t → keep the larger: 0
letterss and t
up0
left0
cell0
s and t differ, so they cannot both end the common subsequence; one of them is left out. Dropping s gives the cell above (0), dropping t gives the cell to the left (0), and the larger, 0, is kept.
LCS length of each pair of prefixesemptyeatemptysea00000000010word1seaword2eatletters match0up-left+1=1e matches e → one more than up-left: 1
letterse and e
cell1
Both prefixes end in e, so this pair of letters can close a common subsequence. The best one without them is the up-left cell (0), and adding the pair makes it 1.
LCS length of each pair of prefixesemptyeatemptysea000000000110word1seaword2eatletters differ0upor1left→1e differs from a → keep the larger: 1
letterse and a
up0
left1
cell1
e and a differ, so they cannot both end the common subsequence; one of them is left out. Dropping e gives the cell above (0), dropping a gives the cell to the left (1), and the larger, 1, is kept.
LCS length of each pair of prefixesemptyeatemptysea0000000001110word1seaword2eatletters differ0upor1left→1e differs from t → keep the larger: 1
letterse and t
up0
left1
cell1
e and t differ, so they cannot both end the common subsequence; one of them is left out. Dropping e gives the cell above (0), dropping t gives the cell to the left (1), and the larger, 1, is kept.
LCS length of each pair of prefixesemptyeatemptysea00000000011101word1seaword2eatletters differ1upor0left→1a differs from e → keep the larger: 1
lettersa and e
up1
left0
cell1
a and e differ, so they cannot both end the common subsequence; one of them is left out. Dropping a gives the cell above (1), dropping e gives the cell to the left (0), and the larger, 1, is kept.
LCS length of each pair of prefixesemptyeatemptysea000000000111012word1seaword2eatletters match1up-left+1=2a matches a → one more than up-left: 2
lettersa and a
cell2
Both prefixes end in a, so this pair of letters can close a common subsequence. The best one without them is the up-left cell (1), and adding the pair makes it 2.
LCS length of each pair of prefixesemptyeatemptysea0000000001110122word1seaword2eatletters differ1upor2left→2a differs from t → keep the larger: 2
lettersa and t
up1
left2
cell2
a and t differ, so they cannot both end the common subsequence; one of them is left out. Dropping a gives the cell above (1), dropping t gives the cell to the left (2), and the larger, 2, is kept.
LCS length of each pair of prefixesemptyeatemptysea0000000001110122word1seaword2eatkept in both: e, a → the rest is deleted
LCS2
Walking back from the bottom-right cell, each matching pair is kept and every other step moves to the larger neighbour. The kept letters (ea) survive in both words, so only the struck-out letters have to go: s from word1 and t from word2.
LCS length of each pair of prefixesemptyeatemptysea0000000001110122word1seaword2eatdeletions3word1+3word2−2 × 2kept twice=2answer: 2 deletions
answer2
The 2 kept letters are in both words, so they come off both lengths: 3 + 3 − 2 × 2 = 2 deletions in total.
05

Common pitfalls

Subtracting the LCS only once

✗ Wrong
return m + n - dp[m][n]
✓ Right
return m + n - 2 * dp[m][n]

The kept letters stay in both words, so they come off both lengths. On sea and eat the LCS is ea, length 2: the wrong line returns 4, but deleting s and t is enough, so the answer is 2.

Reading the words at the table index

✗ Wrong
if word1[i] == word2[j]:
✓ Right
if word1[i - 1] == word2[j - 1]:

Row i stands for the first i letters, so its last letter is word1[i - 1]. Reading word1[i] compares the wrong pair of letters, and at i = m it runs past the end of the word: on sea and eat it raises an IndexError.

06

Edge cases

No letter in common, e.g. ab and cd

No pair ever matches, so every cell stays 0 and the LCS is 0. Every letter has to go, and the answer is 2 + 2 = 4.

One word hidden inside the other, e.g. abc and ac

The LCS is the whole shorter word, so only the longer word loses letters: 3 + 2 − 2 × 2 = 1, deleting the b.

07

Complexity

Time
O(m · n)
Space
O(m · n)
One pass over the (m + 1) × (n + 1) table, with constant work per cell. Each row only reads the row above it, so keeping two rows of n + 1 numbers cuts the space to O(n).
08

Delete Operation for Two Strings FAQ

How is this different from Edit Distance?

Edit Distance also lets you insert and replace a letter, so its table takes a minimum over three moves, one of them a diagonal replace. Here only deleting is allowed, so there is no replace move. On a and b, edit distance is 1 (replace the letter), while this problem needs 2 deletions.

Is it the same table as Longest Common Subsequence?

Yes. Longest Common Subsequence fills exactly this table and returns dp[m][n]; only the last line differs. You can also count deletions directly: set row 0 to j and column 0 to i, copy the up-left cell on a match, and take 1 + min(up, left) otherwise. Both give the same answer.

How do you see which letters get deleted?

Walk back from dp[m][n]. Where the two letters match, keep that letter and step up-left; otherwise step to whichever of up or left holds the larger number. The letters you never kept are the deletions. For sea and eat the walk keeps e and a, so s goes from the first word and t from the second.