Tutorialspoint
Problem
Solution
Submissions

Edit Distance

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the minimum number of operations required to convert string word1 to word2. You have the following three operations permitted on a word: insert a character, delete a character, or replace a character. This is also known as the Levenshtein distance.

Example 1
  • Input: word1 = "horse", word2 = "ros"
  • Output: 3
  • Explanation:
    • Step 1: horse -> rorse (replace 'h' with 'r')
    • Step 2: rorse -> rose (remove 'r')
    • Step 3: rose -> ros (remove 'e')
    • Step 4: Total operations = 3
Example 2
  • Input: word1 = "intention", word2 = "execution"
  • Output: 5
  • Explanation:
    • Step 1: intention -> inention (remove 't')
    • Step 2: inention -> enention (replace 'i' with 'e')
    • Step 3: enention -> exention (replace 'n' with 'x')
    • Step 4: exention -> exection (replace 'n' with 'c')
    • Step 5: exection -> execution (insert 'u')
    • Step 6: Total operations = 5
Constraints
  • 0 ≤ word1.length, word2.length ≤ 500
  • word1 and word2 consist of lowercase English letters
  • Time Complexity: O(m * n)
  • Space Complexity: O(m * n)
StringsDynamic Programming HCL TechnologiesLTIMindtree
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].
  • dp[i][j] represents minimum operations to convert word1[0...i-1] to word2[0...j-1].
  • Initialize base cases: dp[0][j] = j and dp[i][0] = i.
  • If characters match, dp[i][j] = dp[i-1][j-1].
  • If characters don't match, take minimum of three operations plus 1.
  • The three operations are: insert, delete, replace.

Steps to solve by this approach:

 Step 1: Create a 2D DP array where dp[i][j] represents minimum operations to convert word1[0...i-1] to word2[0...j-1].
 Step 2: Initialize base cases - dp[i][0] = i (delete all) and dp[0][j] = j (insert all).
 Step 3: For each cell, check if current characters match.
 Step 4: If characters match, copy value from dp[i-1][j-1] (no operation needed).
 Step 5: If characters don't match, take minimum of three operations (insert, delete, replace) and add 1.
 Step 6: Fill the entire DP table using the recurrence relation.
 Step 7: Return dp[m][n] which contains the minimum edit distance.

Submitted Code :