You are given two 0-indexed strings source and target, both of length
n and consisting of lowercase English characters. You are also given two
0-indexed string arrays original and changed, and an integer array
cost, where cost[i] represents the cost of converting the string
original[i] to the string changed[i].
You start with the string source. In one operation, you can pick a
substringx from the string, and change it to y at a cost of zif there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y. You are allowed to do any number of operations, but any pair of operations must satisfy either of these two conditions:
The substrings picked in the operations are source[a..b] and source[c..d] with either b < cord < a. In other words, the indices picked in both operations are disjoint.
The substrings picked in the operations are source[a..b] and source[c..d] with a == candb == d. In other words, the indices picked in both operations are identical.
Return _theminimum cost to convert the string _sourceto the stringtargetusingany number of operations. If it is impossible to convertsourcetotarget,return-1.
Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].
Input: source ="abcd", target ="acbe", original =["a","b","c","c","e","d"], changed =["b","c","b","e","b","e"], cost =[2,5,5,1,2,20]Output: 28Explanation: To convert "abcd" to "acbe",do the following operations:- Change substring source[1..1] from "b" to "c" at a cost of 5.- Change substring source[2..2] from "c" to "e" at a cost of 1.- Change substring source[2..2] from "e" to "b" at a cost of 2.- Change substring source[3..3] from "d" to "e" at a cost of 20.The total cost incurred is5+1+2+20=28.It can be shown that thisis the minimum possible cost.
Input: source ="abcdefgh", target ="acdeeghh", original =["bcd","fgh","thh"], changed =["cde","thh","ghh"], cost =[1,3,5]Output: 9Explanation: To convert "abcdefgh" to "acdeeghh",do the following operations:- Change substring source[1..3] from "bcd" to "cde" at a cost of 1.- Change substring source[5..7] from "fgh" to "thh" at a cost of 3. We can dothis operation because indices [5,7] are disjoint with indices picked in the first operation.- Change substring source[5..7] from "thh" to "ghh" at a cost of 5. We can dothis operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation.The total cost incurred is1+3+5=9.It can be shown that thisis the minimum possible cost.
Input: source ="abcdefgh", target ="addddddd", original =["bcd","defgh"], changed =["ddd","ddddd"], cost =[100,1578]Output: -1Explanation: It is impossible to convert "abcdefgh" to "addddddd".If you select substring source[1..3] as the first operation to change "abcdefgh" to "adddefgh", you cannot select substring source[3..7] as the second operation because it has a common index,3,with the first operation.If you select substring source[3..7] as the first operation to change "abcdefgh" to "abcddddd", you cannot select substring source[1..3] as the second operation because it has a common index,3,with the first operation.
We want to convert source to target using the minimum cost, where each operation can replace any substring with another at a given cost. This is similar to finding the shortest path in a graph, where each node is a string and edges are substring replacements. To efficiently find applicable substring replacements, we use a Trie to match substrings in source.
classSolution:
defminimumCost(self, source: str, target: str, original: list[str], changed: list[str], cost: list[int]) -> int:
import heapq
if source == target:
return0 n = len(source)
dist: dict[str, int] = {source: 0}
pq: list[tuple[int, str]] = [(0, source)]
while pq:
c, s = heapq.heappop(pq)
if c > dist[s]: continueif s == target: return c
for i in range(n):
for idx, o in enumerate(original):
if i + len(o) <= n and s[i:i+len(o)] == o:
ns = s[:i] + changed[idx] + s[i+len(o):]
nc = c + cost[idx]
if ns notin dist or nc < dist[ns]:
dist[ns] = nc
heapq.heappush(pq, (nc, ns))
return-1
⏰ Time complexity: O(L * M * N log K) where L is the length of the string, M is the number of rules, N is the average length of original[i], and K is the number of unique strings visited.
🧺 Space complexity: O(K) for the heap and visited map.