Skip to main content
Back to problems
#72
Medium Algorithms

Edit distance

String Dynamic Programming
60.2% acceptance
Jan 12, 2026
16335
323
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

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn min_distance(word1: String, word2: String) -> i32 {
    let (m, n) = (word1.len(), word2.len());
    let (word1, word2) = (word1.as_bytes(), word2.as_bytes());
    
    // Space-optimized DP: O(n) instead of O(m*n)
    let mut dp = (0..=n as i32).collect::<Vec<_>>();
    
    for i in 1..=m {
      let mut prev = dp[0];
      dp[0] = i as i32;
      
      for j in 1..=n {
        let temp = dp[j];
        dp[j] = if word1[i-1] == word2[j-1] {
          prev
        } else {
          1 + prev.min(dp[j]).min(dp[j-1])
        };
        prev = temp;
      }
    }
    
    dp[n]
  }
}