
Problem
Solution
Submissions
Edit Distance using Dynamic Programming
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 15
Write a Java program to find the minimum number of operations required to convert one string to another. The allowed operations are:
- 1. Insert a character
- 2. Delete a character
- 3. Replace a character
Each operation has a cost of 1. The goal is to find the minimum edit distance between the two strings.
Example 1
- Input: word1 = "horse", word2 = "ros"
- Output: 3
- Explanation: Replace 'h' with 'r' to get "rorse" Delete 'r' to get "rose" Delete 'e' to get "ros" Total operations needed: 3
Example 2
- Input: word1 = "intention", word2 = "execution"
- Output: 5
- Explanation: Replace 'i' with 'e' to get "entention" Replace 'n' with 'x' to get "extention" Replace 't' with 'e' to get "exeention" Replace 'n' with 'c' to get "execntion" Replace 'i' with 'u' to get "execution" Total operations needed: 5
Constraints
- 0 <= word1.length, word2.length <= 500
- word1 and word2 consist of lowercase English letters
- Time Complexity: O(m * n) where m and n are the lengths of the two strings
- Space Complexity: O(m * n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use a 2D dynamic programming array to store the minimum edit distance between prefixes of the two strings
- Initialize dp[i][0] = i and dp[0][j] = j as base cases
- For each pair of characters, if they are the same, no operation is needed
- If they are different, consider the minimum of the three operations: insert, delete, or replace
- Use the recurrence relation: dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + (word1[i-1] == word2[j-1] ? 0 : 1))
- The final answer will be dp[m][n], where m and n are the lengths of the two strings