02(Aug) Edit Distance
02. Edit Distance
The problem can be found at the following link: Question Link
Problem Description
Given two strings str1 and str2, return the minimum number of operations required to convert str1 to str2. The possible operations are:
Insert a character at any position of the string.
Remove any character from the string.
Replace any character from the string with any other character.
Examples:
Input:
str1 = "geek"
str2 = "gesek"Output:
1Explanation: One operation is required, inserting 's' between two 'e'.
My Approach
Initialization:
Create a 2D vector
dpof size(m+1) x (n+1), wheremis the length ofstr1andnis the length ofstr2.
Base Case:
If
str1is empty (i == 0), the cost is the length ofstr2(all insertions).If
str2is empty (j == 0), the cost is the length ofstr1(all deletions).
DP Transition:
If the current characters of
str1andstr2match (str1[i-1] == str2[j-1]), no new operation is needed. Hence,dp[i][j] = dp[i-1][j-1].If the characters do not match, consider the cost of insertion, deletion, and replacement, and take the minimum:
Insertion:
dp[i][j-1] + 1Deletion:
dp[i-1][j] + 1Replacement:
dp[i-1][j-1] + 1
Return:
The value at
dp[m][n]gives the minimum number of operations required to convertstr1tostr2.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(m * n), where
mis the length ofstr1andnis the length ofstr2.Expected Auxiliary Space Complexity: O(m * n), as we use a 2D vector of size
(m+1) x (n+1).
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated