Skip to content

Commit 73729a3

Browse files
authored
Create 04 - Space Optimized | DP | Approach.cpp
1 parent 3801815 commit 73729a3

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the minimum edit distance using dynamic programming
4+
int solve(string word1, string word2) {
5+
int n = word1.length(); // Length of the first string
6+
int m = word2.length(); // Length of the second string
7+
8+
// Create two 1D arrays to store the current and next row values of the dp table
9+
vector<int> curr(m+1, 0); // Current row (for the current i-th character in word1)
10+
vector<int> next(m+1, 0); // Next row (for the next i+1-th character in word1)
11+
12+
// Initialize the next row for the case when word1 is empty
13+
for(int j = 0; j < m; j++) next[j] = m - j;
14+
15+
// Iterate over word1 from bottom to top (i = n-1 to i = 0)
16+
for(int i = n-1; i >= 0; i--) {
17+
// Iterate over word2 from right to left (j = m-1 to j = 0)
18+
for(int j = m-1; j >= 0; j--) {
19+
// Set the base case for when word2 is empty (fill in the current row's last column)
20+
curr[m] = n - i;
21+
22+
int ans = 0;
23+
// If characters match, take the result from the next row's next column
24+
if(word1[i] == word2[j]) ans = next[j+1];
25+
else {
26+
// Otherwise, calculate the costs of insertion, deletion, and replacement:
27+
int insertAns = 1 + curr[j+1]; // Insert a character from word2 into word1
28+
int deleteAns = 1 + next[j]; // Delete a character from word1
29+
int replaceAns = 1 + next[j+1]; // Replace a character in word1 with word2
30+
31+
// Take the minimum of these three options
32+
ans = min({insertAns, deleteAns, replaceAns});
33+
}
34+
35+
// Store the result for the current cell in the current row
36+
curr[j] = ans;
37+
}
38+
// Update the next row to be the current row after finishing one iteration
39+
next = curr;
40+
}
41+
42+
// The final result is stored in curr[0], which represents the minimum edit distance
43+
return curr[0];
44+
}
45+
46+
// Main function to calculate the minimum edit distance between word1 and word2
47+
int minDistance(string word1, string word2) {
48+
// Edge case: if one of the strings is empty, the result is the length of the other string
49+
if(word1.length() == 0) return word2.length();
50+
if(word2.length() == 0) return word1.length();
51+
52+
// Call the solve function to compute the result
53+
return solve(word1, word2);
54+
}
55+
};

0 commit comments

Comments
 (0)