72. Edit Distance - Detailed Explanation

Problem statement

Description:

Given two strings, word1 and word2, return the minimum number of operations required to convert word1 into word2. You have the following three operations permitted on a word:

  • Insert a character.
  • Delete a character.
  • Replace a character.

Examples:

  1. Example 1:

    • Input: word1 = "horse", word2 = "ros".
    • Output: 3.
    • Explanation: One way to convert "horse" to "ros" is:
      • "horse" → "rorse" (replace 'h' with 'r').
      • "rorse" → "rose" (remove the first 'r').
      • "rose" → "ros" (remove the 'e').
  2. Example 2:

    • Input: word1 = "intention", word2 = "execution".
    • Output: 5.
    • Explanation: One way to convert "intention" to "execution" is:
      • "intention" → "inention" (remove 't').
      • "inention" → "enention" (replace 'i' with 'e').
      • "enention" → "exention" (replace 'n' with 'x').
      • "exention" → "exection" (replace 'n' with 'c').
      • "exection" → "execution" (insert 'u').

Constraints:

  • The lengths of the strings can vary, commonly up to 500 characters in many test cases.
  • Both strings can be empty.

The minimum number of operations between two strings is called the edit distance, or the Levenshtein distance. This question is an instance of multidimensional dynamic programming. Grokking Dynamic Programming teaches it in the Longest Common Substring chapter. Every cell of a table holds the best answer for one pair of prefixes, and the value of a cell is the cheapest of a small set of earlier cells. Edit Distance is also one of the dynamic programming entries on the Blind 75 list, so it is worth being able to write it from memory.

Hints before the solution

  1. Dynamic programming insight: Think about solving the problem for smaller prefixes of the strings. Once you can compute the minimum edit distance for prefixes of word1 and word2, those results build up the answer for the full strings.

  2. Base cases are key: Consider what happens when one of the strings is empty. Converting an empty string to a non-empty string, or the reverse, requires inserting or deleting every character.

  3. Subproblem relationship: If the last characters of the two strings match, the edit distance for the full strings equals the distance for the prefixes without those last characters. If they differ, consider all three operations and take the cheapest.

Approaches

Approach: dynamic programming (bottom-up)

Idea:

  • Define dp[i][j] as the minimum edit distance between the first i characters of word1 and the first j characters of word2.
  • Base cases:
    • dp[0][j] = j, since turning an empty string into a string of length j requires j insertions.
    • dp[i][0] = i, since turning a string of length i into an empty string requires i deletions.
  • Recurrence relation:
    • If the characters match, meaning word1[i-1] == word2[j-1], then dp[i][j] = dp[i-1][j-1] and the operation count does not rise.
    • Otherwise, consider three moves and take the minimum:
      • Insert: dp[i][j-1] + 1.
      • Delete: dp[i-1][j] + 1.
      • Replace: dp[i-1][j-1] + 1.
    • In one line, that is dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 1).

Why it works:

  • The table builds the answer from solutions to smaller subproblems, and each cell is computed only once.
  • Once the dp table is complete, dp[m][n] holds the answer, where m is the length of word1 and n is the length of word2.

Design Gurus teaches this problem in the Edit Distance lesson of Grokking Dynamic Programming, next to the other questions that fill a table over two strings.

Code implementations

Python implementation

Python3
Python3

. . . .

Java implementation

Java
Java

. . . .

Complexity analysis

  • Time complexity:

    • The solution fills a table of size (m+1) x (n+1) with a nested loop, which gives a time complexity of O(m * n).
  • Space complexity:

    • The DP table uses O(m * n) space.
    • Space optimization can reduce that to O(min(m, n)) if needed, since each row depends only on the row above it.

Step-by-step walkthrough with a visual example

Consider converting word1 = "horse" to word2 = "ros":

  1. Initialization:

    • Create a DP table dp with dimensions 6 x 4, since "horse" has 5 characters and "ros" has 3.
    • Set dp[0][j] = j for j from 0 to 3.
    • Set dp[i][0] = i for i from 0 to 5.
  2. Filling the table:

    • For each i from 1 to 5 and each j from 1 to 3, compute dp[i][j].
    • Compare word1[i-1] with word2[j-1].
    • If they are equal, dp[i][j] = dp[i-1][j-1].
    • If they differ, dp[i][j] = min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 1).
  3. Final answer:

    • After the table is complete, the answer sits in dp[5][3], which is 3 for this input.

Common mistakes

  • Incorrect base case initialization: Leaving the first row and the first column unset, or filling them with zeros, produces wrong answers everywhere downstream.

  • Off-by-one errors: Be careful with array indices. The table is one row and one column larger than the string lengths, so that the empty prefix has a row and a column of its own.

  • Ignoring equal characters: Failing to test whether the two characters match adds an operation that is not needed, which overestimates the edit distance.

Edge cases

  • One or both strings empty:

    • If word1 is empty, the answer is the length of word2, all insertions.
    • If word2 is empty, the answer is the length of word1, all deletions.
  • Identical strings: The edit distance is 0, since the diagonal of matches carries every cell forward without a cost.

  • Alternative variation: Some questions ask for the actual sequence of operations rather than the count. Answering that means walking backward through the DP table from dp[m][n] and recording which predecessor cell produced each value.

  • Unique Paths: The Unique Paths answer uses the same two-dimensional table shape, but it adds counts instead of taking a minimum, which is a clean way to see what the table structure does and does not decide.

  • Related problems for further practice:

    • Longest Common Subsequence, the closest relative, since a match on the diagonal plays the same role there.
    • Longest Common Substring, where a mismatch resets the run to zero instead of paying for an operation.
    • Minimum Insertions and Deletions to Transform a String, which is edit distance without the replace move.
    • Sequence Alignment Problems, the same recurrence with per-operation costs that are not all 1.

For the wider map of techniques these questions draw on, the article on the recurring LeetCode patterns sorts dynamic programming into the handful of shapes that keep returning in interviews.

TAGS
Coding Interview Questions
Coding Interview
CONTRIBUTOR
Arslan Ahmad
Arslan Ahmad
ex-FAANG engineering manager and author or Grokking series.

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Who answers Amazon questions?
What protocol does Twilio use?
How to recursively list directories in C on Linux?
What is the golden rule of reviewing?
What is the top salary in Coinbase?
Where to get Node JS coding questions and answers?
Related Courses
New
Grokking the AI System Design Interview course cover
Grokking the AI System Design Interview
Learn to design AI systems the way interviewers expect: classic ML products, LLM and RAG architectures, and agentic systems, all through the lens of the system design interview.
4.6
(3,192 learners)
Discounted price for Your Region

$99

Grokking the Coding Interview: Patterns for Coding Questions course cover
Grokking the Coding Interview: Patterns for Coding Questions
The 24 essential patterns behind every coding interview question. Available in Java, Python, JavaScript, C++, C#, and Go. The most comprehensive coding interview course with 543 lessons. A smarter alternative to grinding LeetCode.
4.6
Discounted price for Your Region

$197

Grokking Modern AI Fundamentals course cover
Grokking Modern AI Fundamentals
Master the fundamentals of AI today to lead the tech revolution of tomorrow.
4.1
Discounted price for Your Region

$72

Design Gurus logo
One-Stop Portal For Tech Interviews.
About Us
Our Team
Careers
Partners
Contact Us
Become Affiliate
Copyright © 2026 Design Gurus, LLC. All rights reserved.