
Problem
Solution
Submissions
Edit Distance Between Two Strings
Certification: Advanced Level
Accuracy: 100%
Submissions: 2
Points: 15
Write a Python function that computes the edit distance between two strings. The edit distance is the minimum number of operations (insertion, deletion, or substitution) required to convert one string into another.
Example 1
- Input: word1 = "horse", word2 = "ros"
- Output: 3
- Explanation:
- Step 1: Create a 2D array dp[len(word1)+1][len(word2)+1].
- Step 2: Fill the matrix using dynamic programming.
- Step 3: For each position, calculate minimum cost of operations.
- Step 4: Transformations needed:
- horse -> rorse (replace 'h' with 'r')
- rorse -> rose (remove 'r')
- rose -> ros (remove 'e')
- Step 5: Total operations: 3
Example 2
- Input: word1 = "intention", word2 = "execution"
- Output: 5
- Explanation:
- Step 1: Create a 2D array for dynamic programming.
- Step 2: Fill the matrix comparing each character.
- Step 3: For each cell, calculate minimum of insert, delete, or replace.
- Step 4: Transformations needed:
- intention -> inention (remove 't')
- inention -> enention (replace 'i' with 'e')
- enention -> exention (replace 'n' with 'x')
- exention -> exection (replace 'n' with 'c')
- exection -> execution (insert 'u')
- Step 5: Total operations: 5
Constraints
- 0 ≤ len(word1), len(word2) ≤ 500
- word1 and word2 consist of lowercase English letters
- Time Complexity: O(m*n), where m and n are the lengths of the input 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 dynamic programming with a 2D array dp[i][j] representing the edit distance between the first i characters of word1 and the first j characters of word2
- Initialize the first row and column of the dp array
- For each character pair, consider three operations: insertion, deletion, and substitution
- The final result will be in dp[m][n]
- Handle empty strings as special cases