Delete Operation for Two Strings
The key idea
The characters you never delete must form a common subsequence of both words, so the fewest deletions keep the longest common subsequence (LCS) and remove everything else: answer = m + n - 2 * LCS(word1, word2).
Problem
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.
In one step, you can delete exactly one character in either string.
Constraints
1 <= word1.length, word2.length <= 500word1andword2consist of only lowercase English letters.
Examples
Input: word1 = "sea", word2 = "eat"
Output: 2
Input: word1 = "leetcode", word2 = "etco"
Output: 4
Input: word1 = "abcde", word2 = "ace"
Output: 2
Complexity
Time: O(m*n) Space: O(m*n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Dynamic Programming problems
- Best Time to Buy and Sell StockEASY
- Best Time to Buy and Sell Stock IIIHARD
- Best Time to Buy and Sell Stock IVHARD
- Best Time to Buy and Sell Stock with CooldownMEDIUM
- Best Time to Buy and Sell Stock with Transaction FeeMEDIUM
- Burst BalloonsHARD
- Climbing StairsEASY
- Coin ChangeMEDIUM
- Coin Change IIMEDIUM
- Combination Sum IVMEDIUM
- Counting BitsEASY
- Decode WaysMEDIUM