
Sponsored
Sponsored
This approach uses a 2D array to store the edit distances between all prefixes of both strings. By building solutions for smaller subproblems, we can efficiently calculate the solution for the entire problem.
We define dp[i][j] as the edit distance between the first i characters of word1 and the first j characters of word2. The recursion is based on comparing the last characters of the current substrings. If they are the same, the edit distance is the same as dp[i-1][j-1], otherwise, we add 1 (to account for an edit operation) and consider the minimum edit distance found after each possible operation: insertion, deletion, or replacement.
Time Complexity: O(m * n) where m and n are the lengths of word1 and word2 respectively, as we compute values for each combination of indices.
Space Complexity: O(m * n) for storing the dp table.
1def minDistance(word1, word2):
2 m, n = len(word1), len(word2)
3 dp = [[0] * (n + 1) for _ in range(m + 1)]
4
5 for i in range(m + 1):
6 dp[i][0] = i
7 for j in range(n + 1):
8 dp[0][j] = j
9
10 for i in range(1, m + 1):
11 for j in range(1, n + 1):
12 if word1[i - 1] == word2[j - 1]:
13 dp[i][j] = dp[i - 1][j - 1]
14 else:
15 dp[i][j] = 1 + min(
16 dp[i - 1][j], # Deletion
17 dp[i][j - 1], # Insertion
18 dp[i - 1][j - 1] # Replacement
19 )
20
21 return dp[m][n]
22This Python implementation uses dynamic programming. We start with initializing a table where each cell dp[i][j] represents the edit distance between the first i characters of word1 and the first j characters of word2.
The base cases are filled as follows: dp[i][0] = i (deleting all i characters of word1 to match an empty word2) and dp[0][j] = j (inserting all j characters of word2 into an empty word1).
We then populate the table by computing the cost of each edit operation and choosing the one with the minimum cost.
This approach uses recursive calls with memoization to effectively reduce the factors of redundant subproblem calculations. We use a hash map or an array to store results of previously encountered subproblems to avoid recalculating them, subsequently turning the recursive depth-first search into a memoized search.
Time Complexity: O(m * n) where m and n are lengths of word1 and word2. Each subproblem is computed once.
Space Complexity: O(m * n) for memoization storage plus recursion call stack space.
1import java.util.HashMap;
2
3
This Java solution implements a top-down recursion with memoization. The primary operation function 'helper' recursively solves the edit distance problem by considering character matches and operations separately.
Memoization is achieved by storing results of subproblems in a HashMap, uniquely keyed by the indices of remaining substrings.