#583
Delete Operation for Two Strings
MediumStringDynamic ProgrammingDynamic ProgrammingLongest Common Subsequence
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n * m) |
💡
Intuition
Time O(n * m)Space O(n * m)
The optimal approach uses dynamic programming to find the longest common subsequence (LCS) of the two strings. The minimum number of deletions required is the sum of the lengths of both strings minus twice the length of the LCS.
⚙️
Algorithm
3 steps- 1Step 1: Create a 2D array dp where dp[i][j] represents the length of the LCS of the first i characters of word1 and the first j characters of word2.
- 2Step 2: Fill the dp array using the following rules: - If characters match (word1[i-1] == word2[j-1]), then dp[i][j] = dp[i-1][j-1] + 1. - If they do not match, then dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
- 3Step 3: The result is calculated as (len(word1) + len(word2) - 2 * dp[len(word1)][len(word2)]).
solution.py15 lines
1# Full working Python code
2
3def min_steps_optimal(word1, word2):
4 m, n = len(word1), len(word2)
5 dp = [[0] * (n + 1) for _ in range(m + 1)]
6
7 for i in range(1, m + 1):
8 for j in range(1, n + 1):
9 if word1[i - 1] == word2[j - 1]:
10 dp[i][j] = dp[i - 1][j - 1] + 1
11 else:
12 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
13
14 lcs_length = dp[m][n]
15 return (m + n - 2 * lcs_length)ℹ
Complexity note: The time complexity is O(n * m) because we fill a 2D array where n and m are the lengths of the two strings. The space complexity is also O(n * m) due to the storage of the dp array.
- 1Understanding the concept of the longest common subsequence (LCS) is crucial for solving this problem efficiently.
- 2Dynamic programming is often used for problems involving sequences and subsequences, as it allows us to build solutions incrementally.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.