Tutorialspoint
Problem
Solution
Submissions

Edit Distance using Dynamic Programming

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

Write a Java program to find the minimum number of operations required to convert one string to another. The allowed operations are:

  • 1. Insert a character
  • 2. Delete a character
  • 3. Replace a character

Each operation has a cost of 1. The goal is to find the minimum edit distance between the two strings.

Example 1
  • Input: word1 = "horse", word2 = "ros"
  • Output: 3
  • Explanation: Replace 'h' with 'r' to get "rorse" Delete 'r' to get "rose" Delete 'e' to get "ros" Total operations needed: 3
Example 2
  • Input: word1 = "intention", word2 = "execution"
  • Output: 5
  • Explanation: Replace 'i' with 'e' to get "entention" Replace 'n' with 'x' to get "extention" Replace 't' with 'e' to get "exeention" Replace 'n' with 'c' to get "execntion" Replace 'i' with 'u' to get "execution" Total operations needed: 5
Constraints
  • 0 <= word1.length, word2.length <= 500
  • word1 and word2 consist of lowercase English letters
  • Time Complexity: O(m * n) where m and n are the lengths of the two strings
  • Space Complexity: O(m * n)
ArraysDynamic Programming IBMDeloitte
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 a 2D dynamic programming array to store the minimum edit distance between prefixes of the two strings
  • Initialize dp[i][0] = i and dp[0][j] = j as base cases
  • For each pair of characters, if they are the same, no operation is needed
  • If they are different, consider the minimum of the three operations: insert, delete, or replace
  • Use the recurrence relation: dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + (word1[i-1] == word2[j-1] ? 0 : 1))
  • The final answer will be dp[m][n], where m and n are the lengths of the two strings


Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][j] represents the minimum edit distance between the first i characters of word1 and first j characters of word2.

 Step 2: Initialize the base cases: dp[i][0] = i (delete i characters) and dp[0][j] = j (insert j characters).
 Step 3: Iterate through both strings character by character.
 Step 4: If the current characters match, no operation is needed, so dp[i][j] = dp[i-1][j-1].
 Step 5: If the characters don't match, consider three operations: - Delete: dp[i-1][j] + 1 - Insert: dp[i][j-1] + 1 - Replace: dp[i-1][j-1] + 1 Choose the minimum of these three.
 Step 6: Fill the entire DP table following the recurrence relation.
 Step 7: Return dp[m][n], which represents the minimum edit distance between the entire strings.

Submitted Code :