Algorithm Day96 - Edit Distance
🧩 Problem
LeetCode 72 - Edit Distance
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:
- Insert a character
- Delete a character
- Replace a character
Example:
1 | Input: word1 = "horse", word2 = "ros" |
💡 Idea
This is a classic dynamic programming problem.
We define dp[i][j] as the minimum number of operations required to convert the first i characters of word1 into the first j characters of word2.
DP Transition
If the characters match (word1[i-1] == word2[j-1]):
1 | dp[i][j] = dp[i-1][j-1] |
Otherwise:
1 | dp[i][j] = 1 + min( |
Base Cases
1 | dp[0][j] = j // need j insertions |
🧠 Complexity
- Time: O(m × n)
- Space: O(m × n)
💻 Java Code
1 | class Solution { |
🏁 Summary
This problem demonstrates how dynamic programming elegantly handles string transformations.
We systematically consider all operations (insert, delete, replace) and store intermediate results to build the final answer efficiently.