AlgoMaster Logo

Edit Distance

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Solution (Basic)

Intuition:

The problem is looking for the minimum number of operations required to convert one string into another. A basic recursive solution would try to define the problem in terms of smaller sub-problems:

  • If the last characters match, no operation is needed for them. Proceed to check the rest of the string.
  • If they don’t match, consider three operations:
    1. Insert a character and check.
    2. Remove a character and check.
    3. Replace a character and check.

The minimum of these operations would be our answer for the sub-problem.

Code:

2. Recursive Solution with Memoization

Intuition:

The basic recursive solution computes the same sub-problems multiple times. Using memoization, we can store the results of already computed sub-problems to avoid redundant calculations, thus optimizing the recursive approach.

Code:

3. Dynamic Programming (Optimal)

Intuition:

The dynamic programming approach iteratively builds up solutions to smaller sub-problems to get the result for the original problem. This reduces the repeated computation caused by recursion.

  • Create a 2D table dp where dp[i][j] represents the edit distance between the first i characters of word1 and the first j characters of word2.
  • The value of dp[i][j] is determined by:
    1. If the characters match, carry forward the diagonal value dp[i-1][j-1].
    2. Else, take the minimum of inserting into dp[i][j-1], removing from dp[i-1][j], or replacing via dp[i-1][j-1] and add 1.

Code: