LeetCode 583: Delete Operation for Two Strings Solution

Master LeetCode problem 583 (Delete Operation for Two Strings), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

583. Delete Operation for Two Strings

Problem Explanation

Explanation

To solve this problem, we can use dynamic programming. We can create a 2D array dp where dp[i][j] represents the minimum number of steps required to make word1[0...i] and word2[0...j] the same.

We can initialize the first row and column of the dp array with values corresponding to deleting characters in word1 or word2 to make them empty strings.

Then, we can iterate through the rest of the dp array. If the characters at word1[i] and word2[j] are the same, we don't need to delete any characters, so dp[i][j] = dp[i-1][j-1]. Otherwise, we need to delete either word1[i] or word2[j], so dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1]).

The final answer will be stored in dp[word1.length()][word2.length()].

The time complexity of this solution is O(mn) where m and n are the lengths of word1 and word2 respectively. The space complexity is also O(mn) for the dp array.

Solution Code

class Solution {
    public int minDistance(String word1, String word2) {
        int m = word1.length();
        int n = word2.length();
        
        int[][] dp = new int[m + 1][n + 1];
        
        for (int i = 0; i <= m; i++) {
            for (int j = 0; j <= n; j++) {
                if (i == 0 || j == 0) {
                    dp[i][j] = i + j;
                } else if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        
        return dp[m][n];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 583 (Delete Operation for Two Strings)?

This page provides optimized solutions for LeetCode problem 583 (Delete Operation for Two Strings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 583 (Delete Operation for Two Strings)?

The time complexity for LeetCode 583 (Delete Operation for Two Strings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 583 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 583 in Java, C++, or Python.

Back to LeetCode Solutions