Edit Distance - Problem

Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.

You have the following three operations permitted on a word:

  • Insert a character
  • Delete a character
  • Replace a character

This problem is also known as the Levenshtein Distance.

Input & Output

Example 1 — Basic Transformation
$ Input: word1 = "horse", word2 = "ros"
Output: 3
💡 Note: horse → rorse (replace 'h' with 'r') → rose (remove 'r') → ros (remove 'e'). Total: 3 operations.
Example 2 — Insert Operations
$ Input: word1 = "intention", word2 = "execution"
Output: 5
💡 Note: intention → inention (delete 't') → enention (replace 'i' with 'e') → exention (replace first 'n' with 'x') → exection (replace 'n' with 'c') → execution (insert 'u'). Total: 5 operations.
Example 3 — Edge Case Empty String
$ Input: word1 = "abc", word2 = ""
Output: 3
💡 Note: Delete all 3 characters from 'abc' to get empty string. Total: 3 operations.

Constraints

  • 0 ≤ word1.length, word2.length ≤ 500
  • word1 and word2 consist of lowercase English letters

Visualization

Tap to expand
Edit Distance (Levenshtein Distance) INPUT word1 = "horse" h o r s e word2 = "ros" r o s Allowed Operations: 1. Insert a character 2. Delete a character 3. Replace a character Goal: Transform word1 to word2 with minimum operations ALGORITHM (DP) 1 Create DP Table dp[i][j] = min ops for word1[0..i] to word2[0..j] 2 Base Cases dp[i][0]=i, dp[0][j]=j 3 Fill Table If chars match: dp[i-1][j-1] Else: 1 + min(ins,del,rep) 4 Result dp[m][n] = answer DP Table: "" r o s "" 0 1 2 3 h 1 1 2 3 o 2 2 1 2 r 3 2 2 2 s 4 3 3 2 e 5 4 4 3 FINAL RESULT Output 3 Transformation Steps: Step 1: Replace 'h' with 'r' horse --> rorse Step 2: Delete 'r' rorse --> rose Step 3: Delete 'e' rose --> ros OK - Verified! Min operations = 3 Time: O(m*n) | Space: O(m*n) Key Insight: The Edit Distance problem exhibits optimal substructure: the solution to aligning two strings depends on solutions to smaller subproblems. dp[i][j] = dp[i-1][j-1] if chars match, otherwise 1 + min of three choices: Insert (dp[i][j-1]), Delete (dp[i-1][j]), or Replace (dp[i-1][j-1]). This avoids exponential recomputation. TutorialsPoint - Edit Distance | Dynamic Programming Approach
Asked in
Google 45 Facebook 38 Microsoft 32 Amazon 28
425.0K Views
High Frequency
~25 min Avg. Time
8.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen