15% off all plans & roadmaps Use code
See plansDelete Operation for Two Strings
Updated
TL;DR: You must delete characters from either string until both match, and the goal is the fewest deletions. The winning idea is a 2D table that finds the longest shared subsequence. Each cell copies its diagonal neighbour on a match and otherwise takes one deletion from the better side.
Problem
Given two strings word1 and word2, return the minimum number of steps needed to make word1 and word2 the same.
In one step, you can delete exactly one character from either string.
Example 1
Input: word1 = "sea", word2 = "eat" Output: 2 Explanation: One step turns "sea" into "ea". Another step turns "eat" into "ea".
Example 2
Input: word1 = "leetcode", word2 = "etco" Output: 4
Constraints
1 <= word1.length, word2.length <= 500word1andword2consist of only lowercase English letters.
Constraints that matter
- Lengths up to 500 mean the table has at most 501 * 501 cells, so an O(m * n) table is cheap.
- Lengths up to 500 rule out plain recursion, because its call count grows exponentially with the lengths.
- Only deletions are allowed, so the answer depends on how many characters the two strings share in order.
- Only lowercase letters means each comparison is a single character check. No hashing or alphabet tricks are needed.
Hints
Hint 1
This problem asks for a common target.
Hint 2
Walk both strings with two indices, starting at the first characters.
Solution
Intuition
This problem asks for a common target. After the deletions, both strings must equal the same string S. The characters you keep from word1 form a subsequence of word1, and the same characters form a subsequence of word2. So the kept characters are a common subsequence of both strings.
Picture a grid where each cell is a sticky note giving the fewest deletions for two word prefixes, so the cell dp[i][j] is that note. A matching letter means you copy the diagonal note for free, while a mismatch costs one more deletion from the better neighbour.
Suppose the longest common subsequence has length L. You delete m - L characters from word1 and n - L characters from word2. The total is m + n - 2 * L, so the job becomes finding L. This is the longest common subsequence pattern, a dynamic programming pattern over two sequences.
The pattern works because the answer for a pair of prefixes depends on smaller pairs of prefixes. Either the last characters match and you keep them, or one of the two last characters must go. A 2D table stores each prefix pair's answer, so you fill it once and read it many times.
Worked example
Input: word1 = "leetcode", word2 = "etco" Output: 4 Explanation: The string "etco" is a subsequence of "leetcode", so the 4 characters e, t, c, o can stay. The other 4 characters of "leetcode" must be deleted, and "etco" needs no deletions. That gives 4 steps in total.
Approach 1: Brute force recursion
Walk both strings with two indices, starting at the first characters. When the current characters match, keeping both is safe, so move both indices forward at no cost. When they differ, one of the two characters must be deleted, so try deleting from each side and keep the cheaper result.
What's slow: the recursion solves the same pair of indices again through different routes. Each mismatch doubles the number of routes, so the same pairs are recomputed many times. Lengths of 500 make this infeasible.
Steps
- Start with indices i = 0 and j = 0 on the first characters of both strings.
- If i has reached the end of word1, return the number of characters left in word2.
- If j has reached the end of word2, return the number of characters left in word1.
- If word1[i] equals word2[j], recurse on (i + 1, j + 1) and return that result with no added cost.
- If they differ, recurse on (i + 1, j) and (i, j + 1), take the smaller result, and add 1.
- Return the result of the call on (0, 0).
Dry run
Trace on word1 = "sea" and word2 = "eat", where the answer is 2.
The call solve(0, 0) compares 's' with 'e'. They differ, so it returns 1 + min(solve(1, 0), solve(0, 1)).
The call solve(1, 0) compares "ea" with "eat". It matches 'e' and 'a', which leaves i = 3 at the end of word1. It then returns n - j = 3 - 2 = 1 for the leftover 't'. So solve(1, 0) = 1.
The call solve(0, 1) compares "sea" with "at". The strings differ, so it spends one step, and it cannot return less than 1 because the strings still differ. The minimum is therefore 1, and solve(0, 0) = 1 + 1 = 2.
Complexity
| Time | O(2^(m + n)) |
|---|---|
| Space | O(m + n) |
Each call advances i, advances j, or advances both, so the recursion depth is at most m + n. A mismatch makes two child calls, and a match makes one, so every node has at most 2 children. A tree of depth d with at most 2 children per node has at most 2^(d + 1) nodes, which gives O(2^(m + n)) time. The call stack holds at most m + n frames at once, so the space is O(m + n), and the exponential time bound is the one that matters.
PythonTested in our runner
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
import sys
sys.setrecursionlimit(10000)
m, n = len(word1), len(word2)
def solve(i: int, j: int) -> int:
# Cost to make word1[i:] and word2[j:] equal
if i == m:
return n - j
if j == n:
return m - i
if word1[i] == word2[j]:
return solve(i + 1, j + 1)
return 1 + min(solve(i + 1, j), solve(i, j + 1))
return solve(0, 0)The 2D Array (Edit Distance / Levenshtein Distance) infographic is part of Pro
A one-page visual of the pattern: when it applies, the steps and the invariant to keep.
Unlock the infographicSolution pattern
2D Array (Edit Distance / Levenshtein Distance)
Approach 2: Bottom-up 2D DP tableOptimal2D Array (Edit Distance / Levenshtein Distance)
What's slow: the brute force recomputes pairs (i, j) for every route that reaches them. There are only (m + 1) * (n + 1) distinct pairs, so most of that work is repeated. The insight that fixes it: the answer for prefixes word1[0..i-1] and word2[0..j-1] depends on only three neighbours, the diagonal cell (i - 1, j - 1), the cell above (i - 1, j) and the cell to the left (i, j - 1). On a match, keep the characters and copy the diagonal; on a mismatch, delete from the better side. Filling row by row makes those neighbours ready before you need them.
Why it is correct. Each cell holds the true minimum for its two prefixes, so the table never stores a guess. If the last characters match, keeping both is never worse than deleting either, so copying the diagonal loses nothing. If they differ, one of them must go, and trying both options and taking the smaller count covers every choice.
Steps
- Let m and n be the lengths. Create a table dp of size (m + 1) by (n + 1), where dp[i][j] is the number of deletions for the prefixes of length i and j.
- Set dp[i][0] = i and dp[0][j] = j. An empty string needs one deletion per character of the other string.
- For i from 1 to m, and for each j from 1 to n, compare word1[i - 1] with word2[j - 1].
- If they match, set dp[i][j] = dp[i - 1][j - 1]. If they differ, set dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]).
- Return dp[m][n].
Dry run
Trace on word1 = "leetcode" and word2 = "etco", where the answer is 4. The table has 9 rows, one for the empty prefix and one for each character of word1. It has 5 columns, one for the empty prefix and one for each character of word2. Each row is shown after it is filled.
| Row i | word1 char | j = 0 | j = 1 (e) | j = 2 (t) | j = 3 (c) | j = 4 (o) |
|---|---|---|---|---|---|---|
| 0 | (empty) | 0 | 1 | 2 | 3 | 4 |
| 1 | l | 1 | 2 | 3 | 4 | 5 |
| 2 | e | 2 | 1 | 2 | 3 | 4 |
| 3 | e | 3 | 2 | 3 | 4 | 5 |
| 4 | t | 4 | 3 | 2 | 3 | 4 |
| 5 | c | 5 | 4 | 3 | 2 | 3 |
| 6 | o | 6 | 5 | 4 | 3 | 2 |
| 7 | d | 7 | 6 | 5 | 4 | 3 |
| 8 | e | 8 | 7 | 6 | 5 | 4 |
Row 1 starts with 'l', which matches nothing in "etco", so each cell is one more than its left neighbour. In row 2, cell j = 1 matches 'e' with 'e', so it copies dp[1][0] = 1. The final cell dp[8][4] = 4, which is the expected output.
Complexity
| Time | O(m * n) |
|---|---|
| Space | O(m * n) |
Let m be the length of word1 and n the length of word2. The two nested loops run m * n times, and each iteration does one comparison and a constant number of array reads and writes. That gives O(m * n) time. The table holds (m + 1) * (n + 1) integers, so the space is O(m * n).
PythonTested in our runner
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
# dp[i][j] = deletions needed to make word1[:i] and word2[:j] equal
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]Common mistakes
- Writing
dp[i][j] = dp[i - 1][j - 1] + 1on a mismatch. That is the edit distance rule with a replacement. This problem allows only deletions, so a mismatch costs 1 + min of the two deletion cells. - Returning the longest common subsequence length L as the answer. The answer is m + n - 2 * L, because each string must lose its characters that are not in the shared subsequence.
- Leaving the first row or column at zero. An empty prefix needs one deletion per character of the other string, so
dp[i][0] = ianddp[0][j] = jmust be set first. - Reading
word1[i]when fillingdp[i][j]. The cell for prefix length i uses character index i - 1, so the fix isword1[i - 1]andword2[j - 1]. - Counting shared letters with a set or a frequency map. The order matters: "ab" and "ba" share letters but need 2 deletions, because only one character can be kept.
- Using
if word1[i - 1] == word2[j - 1]but then taking the minimum even on a match. On a match, copydp[i - 1][j - 1]with no extra cost, because keeping a matching pair never costs a deletion.
Edge cases
- word1 = "a", word2 = "a": the strings are equal, so the answer is 0.
- word1 = "a", word2 = "b": no characters match, so the answer is 2, one deletion from each string.
- word1 = "abc", word2 = "abc": every character matches, so the answer is 0 with no deletions.
- word1 = "abc", word2 = "xyz": nothing is shared, so the answer is 6, which is the total length.
- word1 = "ab", word2 = "ba": the letters match as a set but not in order, so the answer is 2.
- word1 with 500 characters and word2 = "a": the answer is 499 if word1 contains at least one 'a', and 501 otherwise. The table is 501 by 2, so this runs quickly.
Follow-ups interviewers ask
Follow-ups are part of Pro
The questions interviewers ask after you solve Delete Operation for Two Strings, with how to answer them.
Unlock the follow-upsDelete Operation for Two Strings FAQ
What is the time complexity of Delete Operation for Two Strings?
The optimal 2D DP solution runs in O(m * n) time, where m and n are the two string lengths. It fills each of the (m + 1) * (n + 1) cells once, with constant work per cell. The brute force recursion takes O(2^(m + n)) time.
Why use dynamic programming for Delete Operation for Two Strings?
The answer for a pair of prefixes depends on smaller pairs of prefixes. A table stores each pair once, so the same subproblem is never solved twice. Without the table, the recursion repeats work and becomes exponential.
Can Delete Operation for Two Strings be solved in O(1) extra space?
No known method does this for general strings. The DP needs information from the previous row, so a constant amount of memory is not enough. The rolling row version uses O(min(m, n)) space, which is the practical improvement.
Why is the answer m + n - 2 * LCS and not the LCS length?
The LCS is the set of characters you can keep in order. Every other character in word1 and word2 must be deleted, which gives (m - LCS) + (n - LCS) deletions. The DP table computes that total directly, so you do not need the formula in code.
Asked at
See which companies ask this — Pro
Related problems
- Edit Distance · same technique: 2D Array (Edit Distance / Levenshtein Distance)
- Minimum ASCII Delete Sum for Two Strings · same technique: 2D Array (Edit Distance / Levenshtein Distance)
- Regular Expression Matching · same technique: 2D Array (Edit Distance / Levenshtein Distance)
- Coin Change · same pattern: Dynamic Programming (DP) Patterns
- Maximum Subarray · same pattern: Dynamic Programming (DP) Patterns
- Word Break · same pattern: Dynamic Programming (DP) Patterns
- Longest Increasing Subsequence · same pattern: Dynamic Programming (DP) Patterns
- House Robber · same pattern: Dynamic Programming (DP) Patterns
- Longest Common Subsequence · same pattern: Dynamic Programming (DP) Patterns
- Unique Paths · same pattern: Dynamic Programming (DP) Patterns