You are given two 0-indexed stringssource and target, both of length n and consisting of lowercase English letters. You are also given two 0-indexed character arraysoriginal and changed, and an integer arraycost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].
You start with the string source. In one operation, you can pick a character x from the string and change it to the character y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y.
Return the minimum cost to convert the string source to the string target using any number of operations. If it is impossible to convert source to target, return -1.
Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].
💡 Note:Convert 'b'→'c' at position 1 (cost 5), 'd'→'e' at position 3 (cost 20), and 'd'→'b' at position 3. Wait, we need to be more careful. Position 1: b→c (cost 5), Position 3: d→e (cost 20). Total cost = 5 + 20 = 25. Actually checking again: pos 1 b→c cost 5, pos 3 d needs to become e. Looking at conversions, d→e costs 20. But we can do d→c→e which might be cheaper. Let's see: no direct d→c. So d→e costs 20. But wait, we can use d→e directly. Actually, let me recalculate: pos 1: b→c (from original[1]→changed[1], cost[1]=5), pos 3: d→e (cost 20 from original[5]→changed[5], cost[5]=20). But there might be indirect paths. This needs Floyd-Warshall to find optimal.
💡 Note:We can convert a→c (cost 1) and c→b (cost 2), so a→c→b costs 3 total. Each 'a' needs to become 'b', total cost would be 4 × 3 = 12. Wait, that's possible. Let me reconsider... Actually this should return 12, not -1.
The key insight is modeling character conversions as a weighted graph and finding shortest paths. The optimal Floyd-Warshall approach precomputes all shortest paths between character pairs in O(26³) time, then answers each query in O(1). Time: O(26³ + n), Space: O(26²)
Common Approaches
Approach
Time
Space
Notes
✓
Floyd-Warshall All-Pairs Shortest Path
O(26³ + n)
O(26²)
Precompute minimum conversion costs between all character pairs using Floyd-Warshall algorithm
Brute Force DFS
O(n × 26^k)
O(k)
For each character difference, try all possible conversion paths using DFS