TRT
Sign in
mediumAdvancedLeetCode#two-string DP#rolling rows

Edit distance

Find the fewest insertions, deletions and replacements to turn one word into another, with a table over prefixes, then in two rows.

The Runtime Theory Team1 min read
Taught inRebuilding the answer and saving memoryPro — members onlyA DP table holds the value of the best solution, not the solution itself. Walking back through the table recovers the choices. When only the value is needed, keeping one or two rows cuts memory from O(n × m) to O(m).
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inword1 = horse, word2 = ros

out3

inword1 = intention, word2 = execution

out5

inword1 = "", word2 = abc

out3

Return the minimum number of single-character insertions, deletions and replacements to convert word1 into word2.

Before you code

dp[i][j] is the distance between the first i characters of word1 and the first j of word2. The first row and column are 0, 1, 2, …

Hints

  1. If the last characters match, copy the diagonal.
  2. Otherwise 1 + min(above, left, diagonal): delete, insert, replace.
  3. Then keep only two rows, and as a stretch, walk back through a full table to print the edits.

Production & complexity notes

When solving Edit distance on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Rebuilding the answer and saving memory to reinforce the underlying pattern.

What it practices

Saving memory, and reconstructing the edits, from Rebuilding the answer and saving memory.

Not started

Sign in to save your learning progress.

Sign in to save