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
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?
Sources and provenance
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 operation
Already-solved cost
Direction into current cell
Insert second[j-1]
D[i,j-1], then add one
Left
Delete first[i-1]
D[i-1,j], then add one
Above
Replace unequal endpoints
D[i-1,j-1], then add one
Diagonal
Keep equal endpoints
D[i-1,j-1], no new cost
Diagonal
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 prefix
Costs 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.
Match c with cEqual endpoints add no edit: current[1] = previous[0] = 0.
0R12310Q??2???3???
recurrencematch -> diagonal 0columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRow[1,0]operationCostsR matches with zero added cost
Q
not shown→(1, 1)
R
not shown→(0, 0)
base
(0, 0)→not shown
Transform c to cuc differs from u: 1 + min(insert 0, delete 2, replace 1) = 1.
01R2D310I1Q?2???3???
recurrence1 + min(0,2,1) = 1choseninsert ucolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRow[1,0,1]operationCostsI/D/R each add one
Q
(1, 1)→(1, 2)
I
not shown→(1, 1)
D
not shown→(0, 2)
Transform c to cutc differs from t: 1 + min(insert 1, delete 3, replace 2) = 2.
012R3D101I2Q2???3???
recurrence1 + min(1,3,2) = 2choseninsert tcolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRow[1,0,1,2]operationCostsI/D/R each add one
Q
(1, 2)→(1, 3)
I
(1, 1)→(1, 2)
D
(0, 2)→(0, 3)
Transform ca to ca differs from c: 1 + min(insert 2, delete 0, replace 1) = 1.
01231R0D122I1Q??3???
recurrence1 + min(2,0,1) = 1chosendelete acolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[1,0,1,2]currentRow[2,1]operationCostsI/D/R each add one
Q
(1, 3)→(2, 1)
I
(1, 2)→(2, 0)
D
(0, 3)→(1, 1)
Transform ca to cua differs from u: 1 + min(insert 1, delete 1, replace 0) = 1.
012310R1D221I1Q?3???
recurrence1 + min(1,1,0) = 1chosenreplace a with ucolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[1,0,1,2]currentRow[2,1,1]operationCostsI/D/R each add one
Q
(2, 1)→(2, 2)
I
(2, 0)→(2, 1)
D
(1, 1)→(1, 2)
Transform ca to cuta differs from t: 1 + min(insert 1, delete 2, replace 1) = 2.
0123101R2D211I2Q3???
recurrence1 + min(1,2,1) = 2columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[1,0,1,2]currentRow[2,1,1,2]operationCostsI/D/R each add one
Q
(2, 2)→(2, 3)
I
(2, 1)→(2, 2)
D
(1, 2)→(1, 3)
Transform cat to ct differs from c: 1 + min(insert 3, delete 1, replace 2) = 2.
012310122R1D123I2Q??
recurrence1 + min(3,1,2) = 2chosendelete from first prefixcolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[2,1,1,2]currentRow[3,2]operationCostsI/D/R each add one
Q
(2, 3)→(3, 1)
I
(2, 2)→(3, 0)
D
(1, 3)→(2, 1)
Transform cat to cut differs from u: 1 + min(insert 2, delete 1, replace 1) = 2.
0123101221R1D232I2Q?
recurrence1 + min(2,1,1) = 2columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[2,1,1,2]currentRow[3,2,2]operationCostsI/D/R each add one
Q
(3, 1)→(3, 2)
I
(3, 0)→(3, 1)
D
(2, 1)→(2, 2)
Match t with tEqual endpoints copy the diagonal: current[3] = previous[2] = 1. Replace a with u for the one required edit.
01231012211R23221Q
recurrencematch -> diagonal 1result1columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[2,1,1,2]currentRow[3,2,2,1]operationCostsR matches with zero added cost
Q
(3, 2)→(3, 3)
R
(2, 1)→(2, 2)
I
(3, 1)→not shown
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
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.
Match c with cEqual endpoints add no edit: current[1] = previous[0] = 0.
0R12310Q??2???3???
recurrencematch -> diagonal 0columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRow[1,0]operationCostsR matches with zero added cost
Q
not shown→(1, 1)
R
not shown→(0, 0)
base
(0, 0)→not shown
Transform c to cuc differs from u: 1 + min(insert 0, delete 2, replace 1) = 1.
01R2D310I1Q?2???3???
recurrence1 + min(0,2,1) = 1choseninsert ucolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRow[1,0,1]operationCostsI/D/R each add one
Q
(1, 1)→(1, 2)
I
not shown→(1, 1)
D
not shown→(0, 2)
Transform c to cutc differs from t: 1 + min(insert 1, delete 3, replace 2) = 2.
012R3D101I2Q2???3???
recurrence1 + min(1,3,2) = 2choseninsert tcolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[0,1,2,3]currentRow[1,0,1,2]operationCostsI/D/R each add one
Q
(1, 2)→(1, 3)
I
(1, 1)→(1, 2)
D
(0, 2)→(0, 3)
Transform ca to ca differs from c: 1 + min(insert 2, delete 0, replace 1) = 1.
01231R0D122I1Q??3???
recurrence1 + min(2,0,1) = 1chosendelete acolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[1,0,1,2]currentRow[2,1]operationCostsI/D/R each add one
Q
(1, 3)→(2, 1)
I
(1, 2)→(2, 0)
D
(0, 3)→(1, 1)
Transform ca to cua differs from u: 1 + min(insert 1, delete 1, replace 0) = 1.
012310R1D221I1Q?3???
recurrence1 + min(1,1,0) = 1chosenreplace a with ucolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[1,0,1,2]currentRow[2,1,1]operationCostsI/D/R each add one
Q
(2, 1)→(2, 2)
I
(2, 0)→(2, 1)
D
(1, 1)→(1, 2)
Transform ca to cuta differs from t: 1 + min(insert 1, delete 2, replace 1) = 2.
0123101R2D211I2Q3???
recurrence1 + min(1,2,1) = 2columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[1,0,1,2]currentRow[2,1,1,2]operationCostsI/D/R each add one
Q
(2, 2)→(2, 3)
I
(2, 1)→(2, 2)
D
(1, 2)→(1, 3)
Transform cat to ct differs from c: 1 + min(insert 3, delete 1, replace 2) = 2.
012310122R1D123I2Q??
recurrence1 + min(3,1,2) = 2chosendelete from first prefixcolumnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[2,1,1,2]currentRow[3,2]operationCostsI/D/R each add one
Q
(2, 3)→(3, 1)
I
(2, 2)→(3, 0)
D
(1, 3)→(2, 1)
Transform cat to cut differs from u: 1 + min(insert 2, delete 1, replace 1) = 2.
0123101221R1D232I2Q?
recurrence1 + min(2,1,1) = 2columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[2,1,1,2]currentRow[3,2,2]operationCostsI/D/R each add one
Q
(3, 1)→(3, 2)
I
(3, 0)→(3, 1)
D
(2, 1)→(2, 2)
Match t with tEqual endpoints copy the diagonal: current[3] = previous[2] = 1. Replace a with u for the one required edit.
01231012211R23221Q
recurrencematch -> diagonal 1result1columnssecond prefixes: empty, c, cu, cutrowAxisfirst prefixes: empty, c, ca, catpreviousRow[2,1,1,2]currentRow[3,2,2,1]operationCostsR matches with zero added cost
Q
(3, 2)→(3, 3)
R
(2, 1)→(2, 2)
I
(3, 1)→not shown
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 m,n, O(mn+m+n) work includes empty-border handling; row storage is O(n+1) 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.
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.
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 m+n−2⋅LCS(first,second), 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.