
Problem
Solution
Submissions
Edit Distance
Certification: Advanced Level
Accuracy: 0%
Submissions: 0
Points: 15
Write a C program to find the minimum number of operations required to convert string word1 to word2. You have the following three operations permitted on a word: insert a character, delete a character, or replace a character. This is also known as the Levenshtein distance.
Example 1
- Input: word1 = "horse", word2 = "ros"
- Output: 3
- Explanation:
- Step 1: horse -> rorse (replace 'h' with 'r')
- Step 2: rorse -> rose (remove 'r')
- Step 3: rose -> ros (remove 'e')
- Step 4: Total operations = 3
Example 2
- Input: word1 = "intention", word2 = "execution"
- Output: 5
- Explanation:
- Step 1: intention -> inention (remove 't')
- Step 2: inention -> enention (replace 'i' with 'e')
- Step 3: enention -> exention (replace 'n' with 'x')
- Step 4: exention -> exection (replace 'n' with 'c')
- Step 5: exection -> execution (insert 'u')
- Step 6: Total operations = 5
Constraints
- 0 ≤ word1.length, word2.length ≤ 500
- word1 and word2 consist of lowercase English letters
- Time Complexity: O(m * n)
- 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 dynamic programming with a 2D array dp[i][j].
- dp[i][j] represents minimum operations to convert word1[0...i-1] to word2[0...j-1].
- Initialize base cases: dp[0][j] = j and dp[i][0] = i.
- If characters match, dp[i][j] = dp[i-1][j-1].
- If characters don't match, take minimum of three operations plus 1.
- The three operations are: insert, delete, replace.