Leetcode 583. Delete Operation for Two Strings

Problem Explanation

The problem asks to find the minimum number of steps required to make two given strings the same. In each step, you can delete one character in either string.

For example, given the words "sea" and "eat", the minimum number of steps required to make them the same is 2. We can delete 's' from "sea" and 't' from "eat" to make them both "ea".

Solution Approach

To solve the problem, the solution uses the concept of the Longest Common Subsequence (LCS). The LCS of two strings is the longest sequence of characters that appear left-to-right in both the strings (though the sequence does not have to be in contiguous block).

For instance, the LCS for input strings "sea" and "eat" is "ea". Once we find the LCS, we take its length, and subtract it from the lengths of word1 and word2. The sum of these differences is the minimum number of deletions required to make the two strings the same.

The computation of the LCS is done using dynamic programming. The solution initializes a 2D array, dp, where dp[i][j] is the LCS's length of word1[0...i) and word2[0...j). For each character in word1 and word2, if the characters match, dp[i][j] is 1 + dp[i - 1][j - 1]. If the characters do not match, dp[i][j] is the maximum of dp[i - 1][j] and dp[i][j - 1].

Python Solution

3class Solution:
4    def minDistance(self, word1: str, word2: str) -> int:
5        m, n = len(word1), len(word2)
6        dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
7        for i in range(m):
8            for j in range(n):
9                if word1[i] == word2[j]:
10                    dp[i + 1][j + 1] = dp[i][j] + 1
11                else:
12                    dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
13        lcs = dp[m][n]
14        return m + n - 2 * lcs

Java Solution

3class Solution {
4    public int minDistance(String word1, String word2) {
5        int m = word1.length();
6        int n = word2.length();
7        int[][] dp = new int[m + 1][n + 1];
8        for (int i = 0; i < m; i++)
9            for (int j = 0; j < n; j++)
10                if (word1.charAt(i) == word2.charAt(j))
11                    dp[i + 1][j + 1] = dp[i][j] + 1;
12                else
13                    dp[i + 1][j + 1] = Math.max(dp[i][j + 1], dp[i + 1][j]);
14        return m + n - 2 * dp[m][n];
15    }

JavaScript Solution

3var minDistance = function(word1, word2) {
4    let m = word1.length, n = word2.length, dp = Array(m + 1);
5    for(let i = 0; i <= m; i++){
6        if(!dp[i]) dp[i] = Array(n + 1).fill(0);
7        for(let j = 0; j <= n; j++){
8            if(!i || !j) dp[i][j] = 0;
9            else if(word1[i - 1] == word2[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1];
10            else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
11        }
12    }
13    return m + n - 2 * dp[m][n];

In the Java, Python and JavaScript code, first, the lengths of the words are obtained. Then, an array dp is initialized to store the length of the Longest Common Subsequence (LCS) between the prefixes of the two words. If the characters of the two words at the current indices match, the length of the LCS is incremented. If they don't, the LCS length is updated with the maximum length from the last character comparing or from the current character in the other word.

The code finally returns the minimum number of steps required to make the two words the same, calculated as sum of lengths of two strings minus twice the length of their LCS.The concept used in these solutions allows the algorithm to ignore appending any matching characters in both strings, thus optimizing the process and reducing computational burden significantly. Dynamic Programming is particularly useful in such problems where a lot of repeated calculations are involved, and hence is an elegant approach to solve the problem.

We can thus summarize the steps used in the solutions as follows:

  1. Find the lengths of both the strings.
  2. Initialize a 2D dynamic programming table, dp, where each cell dp[i][j] indicates the LCS length for the first i characters of word1 and first j characters of word2.
  3. Iterate through each character in both strings. If the characters match, increment the LCS length. If not, update the LCS length with the maximum length obtained from either ignoring the current character in the first string or in the second string.
  4. Calculate the minimum steps required to make the strings identical as the sum of lengths of the strings minus twice the length of the LCS.

By following these steps, the problems can be solved effectively in Python, Java and JavaScript. This methodology can also be readily extended to other programming languages.

Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.

TA 👨‍🏫