Python

How do you compute the minimum number of insert, delete, or replace operations needed to convert one string into another (e.g., "horse" → "ros")?

December 3, 2025

download ready
Thank You
Your submission has been received.
We will be in touch and contact you soon!

Dynamic programming where DP[i][j] tracks min operations to convert word1[:i] to word2[:j]. Match chars cost 0, mismatch takes min(insert, delete, replace=1). Space optimize to O(min(m,n)) with rolling arrays. O(mn) time. Used in spellcheck (Copilot), fuzzy search (Google), DNA alignment.

Code

def minDistance(word1: str, word2: str) -> int:
    m, n = len(word1), len(word2)
    prev, curr = list(range(n+1)), [0]*(n+1)
    
    for i in range(1, m+1):
        curr[0] = i
        for j in range(1, n+1):
            cost = 0 if word1[i-1] == word2[j-1] else 1
            curr[j] = min(prev[j-1] + cost, prev[j] + 1, curr[j-1] + 1)
        prev, curr = curr, prev
    
    return prev[n]

print(minDistance("horse", "ros"))  # 3
      

Output:-

Explanation ("horse" → "ros"):

Code

h o r s e
↓replace ↓delete ↓delete
r o s
      
  • Replace 'h' → 'r' (1 op)
  • Delete 's' (1 op)
  • Delete 'e' (1 op)Total: 3 operations
Hire Now!

Need Help with Python Development ?

Work with our skilled python developers to accelerate your project and boost its performance.
**Hire now**Hire Now**Hire Now**Hire now**Hire now

How do you compute the minimum number of insert, delete, or replace operations needed to convert one string into another (e.g., "horse" → "ros")?

Dynamic programming where DP[i][j] tracks min operations to convert word1[:i] to word2[:j]. Match chars cost 0, mismatch takes min(insert, delete, replace=1). Space optimize to O(min(m,n)) with rolling arrays. O(mn) time. Used in spellcheck (Copilot), fuzzy search (Google), DNA alignment.

Code

def minDistance(word1: str, word2: str) -> int:
    m, n = len(word1), len(word2)
    prev, curr = list(range(n+1)), [0]*(n+1)
    
    for i in range(1, m+1):
        curr[0] = i
        for j in range(1, n+1):
            cost = 0 if word1[i-1] == word2[j-1] else 1
            curr[j] = min(prev[j-1] + cost, prev[j] + 1, curr[j-1] + 1)
        prev, curr = curr, prev
    
    return prev[n]

print(minDistance("horse", "ros"))  # 3
      

Output:-

Explanation ("horse" → "ros"):

Code

h o r s e
↓replace ↓delete ↓delete
r o s
      
  • Replace 'h' → 'r' (1 op)
  • Delete 's' (1 op)
  • Delete 'e' (1 op)Total: 3 operations