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.
Example 1:
Input: word1 = "sea", word2 = "eat" Output: 2 Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".
Example 2:
Input: word1 = "leetcode", word2 = "etco" Output: 4
Constraints:
1 <= word1.length, word2.length <= 500word1 and word2 consist of only lowercase English letters.This approach is based on finding the Longest Common Subsequence (LCS) between the two given strings. Once we have the LCS, the number of deletions needed is the sum of the lengths of the two strings minus twice the length of the LCS. The LCS represents the longest sequence that both strings have in common without rearranging their order. The deletions from either string will only be those characters not present in the LCS.
Here's a step-by-step process to solve the problem:
dp where dp[i][j] represents the length of LCS of string word1[0...i] and word2[0...j].dp array using the recurrence: if word1[i-1] == word2[j-1], then dp[i][j] = dp[i-1][j-1] + 1; else dp[i][j] = max(dp[i-1][j], dp[i][j-1]).len(word1) + len(word2) - 2 * dp[len(word1)][len(word2)].This implementation computes the length of the Longest Common Subsequence (LCS) by filling up a 2D DP table. The result is derived by subtracting twice the LCS from the total length of the two input strings combined. The table is scanned row by row and filled based on the character match or recursive max value.
C++
Java
Python
C#
JavaScript
Time Complexity: O(m * n), where m and n are the lengths of the two strings.
Space Complexity: O(m * n), as a 2D table is used for storing intermediate results.
DP 30. Minimum Insertions/Deletions to Convert String A to String B • take U forward • 133,681 views views
Watch 9 more video solutions →Practice Delete Operation for Two Strings with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor