The Edit Distance coding problem (also known as Levenshtein distance) asks for the minimum number of operations required to convert one string into another. You are allowed three operations: insert a character, delete a character, or replace a character. Each operation has a cost of 1. The goal is to transform word1 into word2 using the fewest possible moves.
This is one of the most famous dynamic programming interview pattern problems, asked by tech giants like Google, Amazon, and Microsoft. It tests a candidate's ability to identify overlapping subproblems and define a clear state transition. It has real-world applications in spell checkers, DNA sequence alignment, and natural language processing.
The problem is solved using 2D Dynamic Programming.
dp[i][j] as the minimum operations to convert the prefix word1[0...i-1] to word2[0...j-1].j, you need j insertions.i to an empty string, you need i deletions.word1[i-1] == word2[j-1], no operation is needed: dp[i][j] = dp[i-1][j-1].dp[i-1][j] + 1 (Delete)dp[i][j-1] + 1 (Insert)dp[i-1][j-1] + 1 (Replace)Convert "horse" to "ros":
(m+1) x (n+1) to account for empty string states.Be prepared to explain the "intuition" behind each choice in the min() function. For example, why does dp[i][j-1] represent an insertion? (Because you've already matched word1[0...i] with word2[0...j-1], so you just "insert" the character word2[j] into word1).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Decode Ways | Medium | Solve | |
| Interleaving String | Medium | Solve | |
| Longest Palindromic Subsequence | Medium | Solve | |
| Longest Common Subsequence | Medium | Solve | |
| Delete Operation for Two Strings | Medium | Solve |