Problem 583 · LeetCode 583(opens in a new tab)
Delete Operation for Two Strings
MediumDynamic programming
You are given two lowercase words, word1 and word2. In one step you may delete a single letter from either word.
Return the smallest number of steps after which the two words are exactly the same. Deleting every letter is allowed, so two empty words also count as equal.
Example 1
Input: word1 = "cat", word2 = "act" Output: 2 Why: delete "c" from both to get "at"
2 more examples and the constraints
Example 2
Input: word1 = "glass", word2 = "grasp" Output: 4 Why: both become "gas": two deletions from each word
Example 3
Input: word1 = "abc", word2 = "xyz" Output: 6 Why: no letter is shared, so everything goes
Constraints
- 1 ≤ length of word1, length of word2 ≤ 500
- Both words use only the letters a to z
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(m·n)
- Bottom-up tableO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for two 500-letter words | Verdict |
|---|---|---|---|
| Recursion with a memo | O(m·n) | Correct; call overhead | |
| Bottom-up table | O(m·n) | Best; no recursion |
m, n = lengths of word1 and word2.
Edge cases to test
- Identical words. Nothing to delete: 0.
- No shared letters. Delete everything: m + n.
- One word inside the other. "plan" and "planet": delete the extra "e" and "t": 2.
- Repeated letters. "aaa" and "aa" need one deletion; matching any two a's works.
Common mistakes
- Treating it like edit distance with replace: a mismatch costs a deletion here, never a swap.
- Forgetting the base row and column, so dp[i][0] stays 0 instead of i.
- Adding 1 when letters match, instead of copying the diagonal.
How to talk through it
- 1Clarify. Is deletion the only operation? Can a word end up empty?
- 2Think about the last letters. If they match, keep them; if not, one must be deleted.
- 3Write the state. dp[i][j] = fewest deletions for the first i and j letters, with dp[i][0] = i and dp[0][j] = j.
- 4Fill the table. Diagonal on a match, else 1 + min(up, left); the answer is dp[m][n].
- 5Test out loud. Try identical words, words with no shared letters, and one word inside the other.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?