#72

Edit Distance

Medium
StringDynamic ProgrammingDynamic ProgrammingRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(3^n)
O(m * n)
Space
O(n)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

The optimal solution uses dynamic programming to build a table that stores the minimum edit distances for all prefixes of the two strings. This avoids redundant calculations by reusing previously computed results.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a 2D array dp where dp[i][j] represents the edit distance between the first i characters of word1 and the first j characters of word2.
  2. 2Step 2: Initialize the first row and column of the dp array based on the lengths of the strings.
  3. 3Step 3: Fill the dp array using the recurrence relation based on the three operations (insert, delete, replace).
  4. 4Step 4: Return the value in dp[word1.length][word2.length] as the result.
solution.py12 lines
1def minDistance(word1, word2):
2    m, n = len(word1), len(word2)
3    dp = [[0] * (n + 1) for _ in range(m + 1)]
4    for i in range(m + 1): dp[i][0] = i
5    for j in range(n + 1): dp[0][j] = j
6    for i in range(1, m + 1):
7        for j in range(1, n + 1):
8            if word1[i - 1] == word2[j - 1]:
9                dp[i][j] = dp[i - 1][j - 1]
10            else:
11                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
12    return dp[m][n]

Complexity note: The time complexity is quadratic because we fill a 2D table of size m x n, where m and n are the lengths of the two strings. The space complexity is also quadratic due to the storage of the dp table.

  • 1Dynamic programming is essential for optimizing recursive problems.
  • 2Understanding how to build and utilize a table for storing intermediate results is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.