Skip to content
mlmentorship

Edit Distance

Price each final insertion, deletion or replacement from its smaller prefix state, retain two rows, and adapt operation costs or eligibility.

Published · 19 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Edit Distance

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. Two Python strings, first and second. Output. Return the smallest edit count that changes first into exactly second. Rules. Inserting, deleting, or replacing one character costs one; keeping an equal character costs zero. Swapping adjacent characters is not a separate allowed edit. Characters are Python code points without automatic normalization. Preserve both strings. Return a distance, not an edit script or semantic similarity score. Example. "horse" to "ros" returns 3: replace h, delete the extra r, then delete e. Changing "" into "cat" costs 3 insertions.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Fill prefix edit costs: matches copy the diagonal; mismatches add one to min(insert, delete, replace).

Problem trace

Price every final edit from solved prefixes; keep the cheapest and copy matches

Price every final edit from solved prefixes; keep the cheapest and copy matchesEach cell prices possible final edits from solved prefix states. At ca into cu, insertion and deletion each cost two; replacement costs one. The final matching t copies that diagonal without another edit. Empty-prefix borders count insertions or deletions. Keep the previous row intact while building the current row, then commit the completed row. These unit-cost Python-character edits exclude transposition and automatic normalization.Minimum edits between two prefixes,not just endpoint letterscat into cut; unit insertion,deletion, replacementTarget prefixes across; sourceprefixes downemptyccucutempty0123c1R 0D 12ca2I 1Q 12cat3221Q is ca into cu. Price every possiblefinal edit:I left: one2Insertcosts oneD above:one2Deletecosts oneR diagonal:zero1Replacecosts one1ca into cu: one replacement ischeapestThe final t matches: inherit thediagonal11No new editKeep the previous row intact: aboveand diagonal come from it; left comesfrom the growing current row.Commit only after the row iscomplete. Empty into cat costs threeinsertions.Python characters; no automaticnormalization or transposition edit.
Read it this way: Each cell prices possible final edits from solved prefix states. At ca into cu, insertion and deletion each cost two; replacement costs one. The final matching t copies that diagonal without another edit. Empty-prefix borders count insertions or deletions. Keep the previous row intact while building the current row, then commit the completed row. These unit-cost Python-character edits exclude transposition and automatic normalization. Does matching t require another replacement?
Full interview answer 19 min read

Find the minimum number of single-character edits needed to transform one complete string into another.

Problem

Input. Two Python strings, first and second.

Output. Return the smallest edit count that changes first into exactly second.

Rules. Inserting, deleting, or replacing one character costs one; keeping an equal character costs zero. Swapping adjacent characters is not a separate allowed edit. Characters are Python code points without automatic normalization. Preserve both strings. Return a distance, not an edit script or semantic similarity score.

Example. "horse" to "ros" returns 3: replace h, delete the extra r, then delete e. Changing "" into "cat" costs 3 insertions.

Picture

Let D[i,j] be the minimum edits from first[:i] to second[:j]. The two-prefix layout matches LCS, but this objective minimizes transformation cost, not maximizes kept length.

Undo the final operation to find its predecessor:

Final operationAlready-solved costDirection into current cell
Insert second[j-1]D[i,j-1], then add oneLeft
Delete first[i-1]D[i-1,j], then add oneAbove
Replace unequal endpointsD[i-1,j-1], then add oneDiagonal
Keep equal endpointsD[i-1,j-1], no new costDiagonal

These cases cover the final alignment step. Choosing the cheapest predecessor plus its operation cost gives the optimum. Empty-to-prefix borders cost j insertions; prefix-to-empty borders cost i deletions.

For cat to cut, the rows are:

First prefixCosts to "", c, cu, cut
""[0,1,2,3]
c[1,0,1,2]
ca[2,1,1,2]
cat[3,2,2,1]

At ca to cu, predecessor costs are insert one, delete one and replace zero. Replacement therefore costs one. The final equal t copies that diagonal answer. Distance is one, from replacing a with u.

Before appending column j, previous[j] is above, previous[j-1] is diagonal, and current[-1] is left. All are final. Commit previous = current only after completing the row. In the visual, Q is the current cell; I/D/R identify those operation predecessors.

Problem trace

Separate worked strings: preserve previous-row and growing-current-row dependencies

Input and goalFind the fewest insert, delete, or replace steps needed to change one string into another.
Initialize empty-prefix costsFor cat to cut, empty-to-prefix costs are zero through three insertions. Prefix-to-empty costs are zero through three deletions.
Q:0
0base1231???2???3???
columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRownot startedoperationCostsempty-prefix border prices
base
(0, 0)
columns
second prefixes: empty, c, cu, cut
row axis
first prefixes: empty, c, ca, cat

Recognize it
Use it when transforming one sequence prefix into another permits local insert, delete, and replace operations and asks for the minimum total operation count.
Keep true
After current[j] is appended, it is the minimum edits from the processed first prefix to second[:j]; its left, up, and diagonal dependencies are already final.
Reuse it
For minimum transformation problems, define prefix states and map each allowed operation to the predecessor state it leaves behind; then add operation cost to the best predecessor.
For cat to cut, empty-to-prefix costs are zero through three insertions. Prefix-to-empty costs are zero through three deletions. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which predecessor makes the a-to-u mismatch cost one? Why do matching c and t add no edit?
Reference drawing

Problem trace

Price every final edit from solved prefixes; keep the cheapest and copy matches

Price every final edit from solved prefixes; keep the cheapest and copy matchesEach cell prices possible final edits from solved prefix states. At ca into cu, insertion and deletion each cost two; replacement costs one. The final matching t copies that diagonal without another edit. Empty-prefix borders count insertions or deletions. Keep the previous row intact while building the current row, then commit the completed row. These unit-cost Python-character edits exclude transposition and automatic normalization.Minimum edits between two prefixes,not just endpoint letterscat into cut; unit insertion,deletion, replacementTarget prefixes across; sourceprefixes downemptyccucutempty0123c1R 0D 12ca2I 1Q 12cat3221Q is ca into cu. Price every possiblefinal edit:I left: one2Insertcosts oneD above:one2Deletecosts oneR diagonal:zero1Replacecosts one1ca into cu: one replacement ischeapestThe final t matches: inherit thediagonal11No new editKeep the previous row intact: aboveand diagonal come from it; left comesfrom the growing current row.Commit only after the row iscomplete. Empty into cat costs threeinsertions.Python characters; no automaticnormalization or transposition edit.
Execution trace
Input and goalFind the fewest insert, delete, or replace steps needed to change one string into another.
Initialize empty-prefix costsFor cat to cut, empty-to-prefix costs are zero through three insertions. Prefix-to-empty costs are zero through three deletions.
Q:0
0base1231???2???3???
columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRownot startedoperationCostsempty-prefix border prices
base
(0, 0)
columns
second prefixes: empty, c, cu, cut
row axis
first prefixes: empty, c, ca, cat

Recognize it
Use it when transforming one sequence prefix into another permits local insert, delete, and replace operations and asks for the minimum total operation count.
Keep true
After current[j] is appended, it is the minimum edits from the processed first prefix to second[:j]; its left, up, and diagonal dependencies are already final.
Reuse it
For minimum transformation problems, define prefix states and map each allowed operation to the predecessor state it leaves behind; then add operation cost to the best predecessor.
For cat to cut, empty-to-prefix costs are zero through three insertions. Prefix-to-empty costs are zero through three deletions. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which predecessor makes the a-to-u mismatch cost one? Why do matching c and t add no edit?
Read it this way: Each cell prices possible final edits from solved prefix states. At ca into cu, insertion and deletion each cost two; replacement costs one. The final matching t copies that diagonal without another edit. Empty-prefix borders count insertions or deletions. Keep the previous row intact while building the current row, then commit the completed row. These unit-cost Python-character edits exclude transposition and automatic normalization. Does matching t require another replacement?

Code

def edit_distance(first: str, second: str) -> int:
   previous = list(range(len(second) + 1))

   for first_index, first_char in enumerate(first, 1):
      current = [first_index]
      for second_index, second_char in enumerate(second, 1):
         if first_char == second_char:
            current.append(previous[second_index - 1])
         else:
            insert = current[-1]
            delete = previous[second_index]
            replace = previous[second_index - 1]
            current.append(1 + min(insert, delete, replace))
      previous = current

   return previous[-1]

Cost: For lengths , work includes empty-border handling; row storage is slots. Unit-cost symmetry permits swapping strings to store the shorter axis. The source does not perform that swap. Recovering an edit script needs additional reconstruction state or another algorithm.

Change Operation Prices or Eligibility

Start from edit_distance. Keep the prefix meaning and row dependencies, but change each transition together with its border prices.

  1. Use different operation costs.

    New task: Minimize nonnegative insertion, deletion and replacement prices rather than operation count.

    Picture and change: Charge each edge separately. Empty-to-prefix uses insertion prices; prefix-to-empty uses deletion prices. Compare all transitions, with zero diagonal cost for equal characters.

    Code: Complete replacement. Costs must be finite and nonnegative:

    def weighted_edit_distance(first, second, insert_cost, delete_cost, replace_cost):
       previous = [index * insert_cost for index in range(len(second) + 1)]
       for first_index, first_char in enumerate(first, 1):
          current = [first_index * delete_cost]
          for second_index, second_char in enumerate(second, 1):
             current.append(min(
                current[-1] + insert_cost,
                previous[second_index] + delete_cost,
                previous[second_index - 1] + (
                   0 if first_char == second_char else replace_cost
                ),
             ))
          previous = current
       return previous[-1]

    Check: a to b, prices (1,1,3), costs two: delete then insert beats replacement. Empty to ab, prices (2,5,1), costs four, not two.

    Use when: Prices change while eligible edits stay the same. Time and row-slot bounds remain unchanged, excluding numeric bit costs.

  2. Forbid replacement.

    New task: Permit insertion and deletion only.

    Picture and change: Remove the mismatch diagonal alternative. Equal endpoints still match for free; borders stay unit-priced.

    Code: Complete replacement:

    def insert_delete_distance(first, second):
       previous = list(range(len(second) + 1))
       for first_index, first_char in enumerate(first, 1):
          current = [first_index]
          for second_index, second_char in enumerate(second, 1):
             if first_char == second_char:
                current.append(previous[second_index - 1])
             else:
                current.append(1 + min(current[-1], previous[second_index]))
          previous = current
       return previous[-1]

    Check: cat to cut now costs two, as does a to b. This operation set satisfies , unlike replacement-enabled distance.

    Use when: Operation eligibility changes. The original row bounds still apply.

Rebuild Transformation Direction

What must change when swapping strings with asymmetric prices?

Answer: Exchange insertion and deletion prices too. Reversing direction exchanges those operations; swapping only strings changes the priced problem.