#583
Medium Algorithms Delete operation for two strings
String Dynamic Programming
65.3% acceptance
Jan 13, 2026
6142
93
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.
In one step, you can delete exactly one character in either string.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn min_distance(word1: String, word2: String) -> i32 {
let w1: Vec<u8> = word1.bytes().collect();
let w2: Vec<u8> = word2.bytes().collect();
let (m, n) = (w1.len(), w2.len());
let mut dp = vec![vec![0usize; n + 1]; m + 1];
for i in 1..=m {
for j in 1..=n {
dp[i][j] = if w1[i-1] == w2[j-1] {
dp[i-1][j-1] + 1
} else {
dp[i-1][j].max(dp[i][j-1])
};
}
}
let lcs = dp[m][n] as i32;
(m as i32 - lcs) + (n as i32 - lcs)
}
}