Tutorialspoint
Problem
Solution
Submissions

Edit Distance Between Two Strings

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python function that computes the edit distance between two strings. The edit distance is the minimum number of operations (insertion, deletion, or substitution) required to convert one string into another.

Example 1
  • Input: word1 = "horse", word2 = "ros"
  • Output: 3
  • Explanation:
    • Step 1: Create a 2D array dp[len(word1)+1][len(word2)+1].
    • Step 2: Fill the matrix using dynamic programming.
    • Step 3: For each position, calculate minimum cost of operations.
    • Step 4: Transformations needed:
      • horse -> rorse (replace 'h' with 'r')
      • rorse -> rose (remove 'r')
      • rose -> ros (remove 'e')
    • Step 5: Total operations: 3
Example 2
  • Input: word1 = "intention", word2 = "execution"
  • Output: 5
  • Explanation:
    • Step 1: Create a 2D array for dynamic programming.
    • Step 2: Fill the matrix comparing each character.
    • Step 3: For each cell, calculate minimum of insert, delete, or replace.
    • Step 4: Transformations needed:
      • intention -> inention (remove 't')
      • inention -> enention (replace 'i' with 'e')
      • enention -> exention (replace 'n' with 'x')
      • exention -> exection (replace 'n' with 'c')
      • exection -> execution (insert 'u')
    • Step 5: Total operations: 5
Constraints
  • 0 ≤ len(word1), len(word2) ≤ 500
  • word1 and word2 consist of lowercase English letters
  • Time Complexity: O(m*n), where m and n are the lengths of the input strings
  • Space Complexity: O(m*n)
ArraysStringsDynamic Programming FacebookGoldman Sachs
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming with a 2D array dp[i][j] representing the edit distance between the first i characters of word1 and the first j characters of word2
  • Initialize the first row and column of the dp array
  • For each character pair, consider three operations: insertion, deletion, and substitution
  • The final result will be in dp[m][n]
  • Handle empty strings as special cases

Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][j] represents edit distance between word1[0...i-1] and word2[0...j-1].
 Step 2: Initialize first row and column to represent deletions and insertions.
 Step 3: For each cell, if characters match, copy the diagonal value (dp[i-1][j-1]).
 Step 4: If characters don't match, take minimum of insert, delete, and replace operations, plus 1.
 Step 5: Fill the entire DP table bottom-up.
 Step 6: Return the value at dp[m][n] as the minimum edit distance.

Submitted Code :