πDay 7. Edit Distance π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given two strings s1 and s2, you need to find the minimum number of operations required to convert s1 into s2. The valid operations are:
Insert a character at any position.
Delete any character from the string.
Replace any character with another character.
π Example Walkthrough:
Example 1:
Input:
s1 = "geek"
s2 = "gesek"Output:
1Explanation:
We can insert 's' between the two 'e' in "geek" to form "gesek".
Example 2:
Input:
Output:
Explanation:
The strings are already the same, so 0 operations are required.
Example 3:
Input:
Output:
Explanation:
Remove
'a'from "abcd" β "bcd"Replace
'd'with'f'β "bcf"Insert
'e'at the end β "bcfe"
Constraints:
$(1 \leq s1.length(), s2.length() \leq 10^3)$
Both strings are in lowercase.
π― My Approach:
Space-Optimized Dynamic Programming
We use two 1D arrays (
prevandcurr) of size ( n+1 ) (where ( n ) is the length of ( s2 )).Initialize the
prevarray such thatprev[j] = j, meaning if ( s1 ) is empty, it takesjoperations (all inserts) to match ( s2[0..j-1] ).Iterate over each character in ( s1 ) (index
i) and fillcurr:curr[0] = i(if ( s2 ) is empty, we needideletions to match).For each
jin ( s2 ), compares1[i-1]withs2[j-1]:If they match, carry over
prev[j-1].Otherwise,
curr[j] = 1 + min({ replace, delete, insert }).
Swap
prevandcurrafter each iteration to save space.Finally,
prev[n]holds the edit distance.
Algorithm Steps:
Let $( m = \text{length}(s1), n = \text{length}(s2) )$.
Initialize
prevarray of size ( n+1 ) withprev[j] = j.Loop
ifrom1tom:Set
curr[0] = i.For each
jfrom1ton:If
s1[i-1] == s2[j-1], thencurr[j] = prev[j-1].Else
curr[j] = 1 + min( prev[j-1], prev[j], curr[j-1] ).
Swap
prevandcurr.
Answer is
prev[n].
π Time and Auxiliary Space Complexity
Expected Time Complexity: $( O(M \times N) )$, as we iterate through each character of $( s1 )$ and $( s2 )$.
Expected Auxiliary Space Complexity: $( O(N) )$, because we only keep two 1D arrays of size $( n+1 )$.
π Solution Code
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