Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 72 Edit Distance - Walkthrough

Tracing transformations

Trace Edit Distance on s1="horse"s_1 = \text{"horse"} and s2="ros"s_2 = \text{"ros"}. Operations: insert, delete, replace. dp[i][j]dp[i][j] = min operations to transform s1[0..i1]s_1[0..i-1] to s2[0..j1]s_2[0..j-1]. If chars match: dp[i][j]=dp[i1][j1]dp[i][j] = dp[i-1][j-1]. Otherwise: dp[i][j]=1+min(dp[i1][j],dp[i][j1],dp[i1][j1])dp[i][j] = 1 + \min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]).

Answer: dp[5][3]=3dp[5][3] = 3. Operations: replace 'h' with 'r', remove 'r', remove 'e'. Or: remove 'h', replace 'r' with 'r', remove 'e'.