Minimum Cost to Transform One String into Another
Dynamic ProgrammingAuto-graded · 17 test casesLast updated
Tests string DP by computing the minimum total cost to convert a source string into a target string using per-character insert, delete, and replace operations with custom costs.
Minimum Cost to Transform One String into Another
You are given two strings, source and target, and three dictionaries that describe the cost of editing characters:
insert_cost: maps a charactercto the cost of insertingcinto the string.delete_cost: maps a charactercto the cost of deletingcfrom the string.replace_cost: maps a pair"ab"(a two-character string) to the cost of replacing characterawith characterb.
Your task is to find the minimum total cost to transform source into target using any sequence of the three operations above.
Operations
| Operation | Meaning | Cost |
|---|---|---|
Insert c | Insert character c at any position | insert_cost.get(c, 0) |
Delete c | Delete character c from the current string | delete_cost.get(c, 0) |
Replace a → b | Replace character a with character b | replace_cost.get(a+b, 0) |
- Any character or pair not present in the respective dictionary has cost 0 for that operation.
- A replace operation where
a == bis allowed but pointless; its cost equalsreplace_cost.get(a+a, 0). - You want the minimum-cost sequence of operations (each applied one at a time) to turn
sourceexactly intotarget.
Constraints
0 ≤ len(source), len(target) ≤ 2000- All strings and dictionary keys consist of lowercase English letters only.
- All cost values are non-negative integers.
insert_cost,delete_cost, andreplace_costcontain only lowercase-letter keys / two-lowercase-letter keys respectively.- If both strings are empty, the answer is
0. - If
sourceis empty, the only option is to insert every character oftarget. - If
targetis empty, the only option is to delete every character ofsource.
Examples
Example 1
Input: min_transform_cost('cat', 'cut', {'i': 2, 'u': 3}, {'a': 1, 't': 5}, {'au': 2, 'ua': 2})
Output: 0
Example 2
Input: min_transform_cost('abc', 'abc', {'a': 10}, {'a': 10}, {})
Output: 0
Example 3
Input: min_transform_cost('', 'hello', {'h': 1, 'e': 2, 'l': 3, 'o': 4}, {}, {})
Output: 13
Hints
Hint 1
Think of the classic edit-distance DP table where dp[i][j] is the minimum cost to transform source[:i] into target[:j]. What are the three transitions that fill each cell?
Hint 2
For each cell (i, j) you have three choices: delete source[i-1] (come from dp[i-1][j]), insert target[j-1] (come from dp[i][j-1]), or replace source[i-1] with target[j-1] (come from dp[i-1][j-1]). Replacing with the same character is valid but you should also consider if replace is cheaper or more expensive than delete+insert.
Hint 3
Make sure your base cases handle transforming an empty source into a non-empty target (sum of insert costs) and a non-empty source into an empty target (sum of delete costs).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem is a generalization of the classic weighted edit distance (Levenshtein distance). The standard edit-distance DP works perfectly here, with all operation costs replaced by per-character lookups.
DP Definition
Let dp[i][j] = minimum cost to transform source[:i] into target[:j].
Base Cases
dp[0][0] = 0— two empty strings, no work needed.dp[i][0]= cost to delete all ofsource[:i]= sum ofdelete_cost[source[k]]forkin0..i-1.dp[0][j]= cost to insert all oftarget[:j]= sum ofinsert_cost[target[k]]forkin0..j-1.
Transitions
For each (i, j) with i ≥ 1, j ≥ 1, let sc = source[i-1], tc = target[j-1]:
- Delete
sc:dp[i-1][j] + delete_cost.get(sc, 0) - Insert
tc:dp[i][j-1] + insert_cost.get(tc, 0) - Replace
sc → tc:dp[i-1][j-1] + replace_cost.get(sc+tc, 0)
dp[i][j] = min(option 1, option 2, option 3)
Note: when sc == tc, option 3 still works correctly because replace_cost.get(sc+sc, 0) defaults to 0, making it free — which is exactly right (no change needed for matching characters, unless the user explicitly assigned a cost to same-character replacement).
Why It's Correct
Every transformation of source into target corresponds to a sequence of edits that can be read off from the DP table alignment. The DP exhaustively considers all ways to align the two strings and picks the cheapest, so it finds the global optimum.
Complexity
- Time: O(m × n) where m = len(source), n = len(target). Up to ~4 × 10⁶ for 2000 × 2000.
- Space: O(m × n) for the table. (Could be reduced to O(min(m,n)) with rolling arrays, but full table is clear and sufficient.)
from typing import List
def min_transform_cost(source: str, target: str, insert_cost: dict, delete_cost: dict, replace_cost: dict) -> int:
m, n = len(source), len(target)
# dp[i][j] = min cost to transform source[:i] into target[:j]
dp = [[0] * (n + 1) for _ in range(m + 1)]
# Base case: transform source[:i] into empty string -> delete all
for i in range(1, m + 1):
dp[i][0] = dp[i - 1][0] + delete_cost.get(source[i - 1], 0)
# Base case: transform empty string into target[:j] -> insert all
for j in range(1, n + 1):
dp[0][j] = dp[0][j - 1] + insert_cost.get(target[j - 1], 0)
for i in range(1, m + 1):
for j in range(1, n + 1):
sc = source[i - 1]
tc = target[j - 1]
# Option 1: delete source[i-1]
cost_delete = dp[i - 1][j] + delete_cost.get(sc, 0)
# Option 2: insert target[j-1]
cost_insert = dp[i][j - 1] + insert_cost.get(tc, 0)
# Option 3: replace source[i-1] with target[j-1]
cost_replace = dp[i - 1][j - 1] + replace_cost.get(sc + tc, 0)
dp[i][j] = min(cost_delete, cost_insert, cost_replace)
return dp[m][n]