LeetCode Problem

How to Solve Edit Distance

This problem requires calculating the minimum edits needed to convert word1 into word2 using insertions, deletions, and replacements. A state transition dynamic programming approach efficiently captures overlapping subproblems by storing intermediate results. Tracking these transitions ensures correct computation even for strings up to 500 characters, avoiding redundant recursion and making the solution practical for interview scenarios.

GhostInterview Help

Need help with Edit Distance without spending extra time grinding it?

GhostInterview can read Edit Distance from a screenshot, generate the answer path, explain the complexity, and support solver-first interview workflows when you need direct help fast.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.

Problem #72State transition dynamic programmingReviewed 2026-03-08
Difficulty
Medium
Primary pattern
State transition dynamic programming
Answer-first problem summary
Step-by-step approach and complexity
GhostInterview solver workflow

This problem requires calculating the minimum edits needed to convert word1 into word2 using insertions, deletions, and replacements. A state transition dynamic programming approach efficiently captures overlapping subproblems by storing intermediate results. Tracking these transitions ensures correct computation even for strings up to 500 characters, avoiding redundant recursion and making the solution practical for interview scenarios.

Problem Statement

Given two strings, word1 and word2, determine the minimum number of operations required to convert word1 into word2. Allowed operations include inserting a character, deleting a character, or replacing a character.

Return the minimum total operations needed. For example, converting 'horse' to 'ros' involves replacing 'h' with 'r', then deleting 'r' and 'e', yielding 3 operations. Input strings have lengths up to 500 and contain only lowercase English letters.

Examples

Example 1

Input: word1 = "horse", word2 = "ros"

Output: 3

horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')

Example 2

Input: word1 = "intention", word2 = "execution"

Output: 5

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

  • 0 <= word1.length, word2.length <= 500
  • word1 and word2 consist of lowercase English letters.

Solution Approach

Define the DP State

Let dp[i][j] represent the minimum operations to convert the first i characters of word1 to the first j characters of word2. This state captures all previous edits and sets up the framework for state transitions.

State Transition Formula

For each dp[i][j], if word1[i-1] equals word2[j-1], then dp[i][j] = dp[i-1][j-1]; otherwise, dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]), corresponding to deletion, insertion, or replacement.

Implementation and Space Optimization

Iteratively fill the dp table from base cases: dp[0][j] = j and dp[i][0] = i. For large strings, reduce space from O(m*n) to O(min(m,n)) by storing only the previous row, maintaining correctness while saving memory.

Complexity Analysis

MetricValue
TimeDepends on the final approach
SpaceDepends on the final approach

Time complexity is O(mn) because each subproblem dp[i][j] is computed once, iterating through all i x j combinations. Space complexity is O(mn) for the full DP table, or O(min(m,n)) if optimized to store only one previous row, which is critical for long strings.

What Interviewers Usually Probe

  • Asks how the DP table represents overlapping subproblems and why it's necessary.
  • Checks if you can optimize space for large input strings up to 500 characters.
  • Inquires about handling equal characters and how it affects the state transition.

Common Pitfalls or Variants

Common pitfalls

  • Failing to initialize base cases correctly, leading to off-by-one errors in dp[0][j] or dp[i][0].
  • Confusing insertion and deletion operations, which can produce incorrect minimal edits.
  • Attempting recursive solutions without memoization, causing exponential time complexity and timeouts.

Follow-up variants

  • Compute edit distance with only insertions and deletions allowed, ignoring replacements.
  • Find all sequences of operations that achieve the minimum edit distance.
  • Apply edit distance to detect approximate string matching in a text or DNA sequence.

How GhostInterview Helps

  • GhostInterview provides step-by-step DP table construction to track state transitions efficiently.
  • It highlights the minimum operation choice at each step, avoiding common missteps in insertion, deletion, and replacement handling.
  • The solver visualizes space optimization options and shows their impact on large inputs, ensuring practical interview solutions.

Topic Pages

FAQ

What is the main pattern behind the Edit Distance problem?

The main pattern is state transition dynamic programming, where each subproblem depends on previous states representing partial string conversions.

Can the space complexity be reduced for Edit Distance?

Yes, by storing only the previous DP row, space can be reduced from O(m*n) to O(min(m,n)) without affecting correctness.

How do insertions, deletions, and replacements relate in the DP formula?

They correspond to dp[i-1][j] for deletion, dp[i][j-1] for insertion, and dp[i-1][j-1] for replacement, ensuring each choice is counted correctly.

What are common mistakes in implementing Edit Distance?

Typical mistakes include off-by-one errors, confusing insertion with deletion, and using recursive approaches without memoization.

Is Edit Distance suitable for strings of length 500?

Yes, the DP solution handles up to 500 characters efficiently, especially when optimized for space using only one previous row.

GhostInterview Solver

Need direct help with Edit Distance instead of spending more time grinding it?

Download GhostInterview when you want a LeetCode solver, not another long practice loop. Capture Edit Distance from a screenshot, get the answer path and complexity, and use supported stealth workflows that stay outside captured layers.

Screenshot Input

Capture the prompt fast instead of rewriting the problem by hand.

Answer + Complexity

Get the solution path, trade-offs, and complexity summary in one pass.

Stealth Workflow

Stay outside captured layers on supported screen-share workflows.