Minimum Cost to Convert String I (LeetCode 2976): Solution and Explanation
Each rule changes one letter into another for a price. Find the cheapest way to turn source into target position by position, or return -1. Because conversions can chain through other letters, this is an all-pairs shortest path problem on a graph with only 26 nodes.
Intuition
Positions do not affect each other: changing index 3 never helps or hurts index 5. So the total cost is a sum, over positions, of the cheapest way to turn source[p] into target[p].
A rule original[i] -> changed[i] with price cost[i] is a directed edge in a graph whose nodes are the 26 letters. Turning letter x into letter y is a walk along edges, and the cheapest one is a shortest path. A chain like c -> e -> b can beat a direct c -> b rule.
Many positions ask about the same pair of letters, so compute every pair's shortest distance once. With 26 nodes, Floyd-Warshall does that in 26^3, about 17,600 steps, regardless of how long the strings are.
Then walking the strings is a table lookup per position. A single unreachable pair makes the whole conversion impossible.
Approach: Floyd-Warshall on letters
- Make a 26 x 26 table
distfilled with infinity and setdist[i][i] = 0. - For each rule set
dist[a][b] = min(dist[a][b], cost), since a pair may repeat with different prices. - For each pivot
k, and eachi,j, updatedist[i][j]withdist[i][k] + dist[k][j]when that is smaller. - For each position add
dist[source[p]][target[p]]to a 64-bit total, returning -1 if it is infinite. - Return the total.
Step-by-step example
source = "abcd", target = "acbe", rules a->b 2, b->c 5, c->b 5, c->e 1, e->b 2, d->e 20
- Direct roads: a->b 2, b->c 5, c->b 5, c->e 1, e->b 2, d->e 20.
- Pivot b: a->c becomes 2 + 5 = 7. Pivot c: a->e = 8, b->e = 6, and other pairs improve.
- Pivot e: c->b drops from 5 to 1 + 2 = 3, d->b becomes 22.
- Positions: a->a 0, b->c 5, c->b 3, d->e 20.
- Total 0 + 5 + 3 + 20 = 28.
Code: Python, Java, C++
1class Solution:
2 def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int:
3 INF = float('inf')
4 dist = [[INF] * 26 for _ in range(26)]
5 for i in range(26):
6 dist[i][i] = 0
7 for u, v, w in zip(original, changed, cost):
8 a, b = ord(u) - 97, ord(v) - 97
9 dist[a][b] = min(dist[a][b], w)
10 for k in range(26):
11 for i in range(26):
12 if dist[i][k] == INF:
13 continue
14 for j in range(26):
15 if dist[i][k] + dist[k][j] < dist[i][j]:
16 dist[i][j] = dist[i][k] + dist[k][j]
17 total = 0
18 for s, t in zip(source, target):
19 d = dist[ord(s) - 97][ord(t) - 97]
20 if d == INF:
21 return -1
22 total += d
23 return total1class Solution {
2 public long minimumCost(String source, String target, char[] original, char[] changed, int[] cost) {
3 long INF = Long.MAX_VALUE / 4;
4 long[][] dist = new long[26][26];
5 for (int i = 0; i < 26; i++) {
6 Arrays.fill(dist[i], INF);
7 dist[i][i] = 0;
8 }
9 for (int e = 0; e < cost.length; e++) {
10 int a = original[e] - 'a', b = changed[e] - 'a';
11 dist[a][b] = Math.min(dist[a][b], cost[e]);
12 }
13 for (int k = 0; k < 26; k++) {
14 for (int i = 0; i < 26; i++) {
15 if (dist[i][k] == INF) continue;
16 for (int j = 0; j < 26; j++) {
17 if (dist[i][k] + dist[k][j] < dist[i][j]) {
18 dist[i][j] = dist[i][k] + dist[k][j];
19 }
20 }
21 }
22 }
23 long total = 0;
24 for (int p = 0; p < source.length(); p++) {
25 long d = dist[source.charAt(p) - 'a'][target.charAt(p) - 'a'];
26 if (d == INF) return -1;
27 total += d;
28 }
29 return total;
30 }
31}1class Solution {
2public:
3 long long minimumCost(string source, string target, vector<char>& original, vector<char>& changed, vector<int>& cost) {
4 const long long INF = LLONG_MAX / 4;
5 vector<vector<long long>> dist(26, vector<long long>(26, INF));
6 for (int i = 0; i < 26; i++) {
7 dist[i][i] = 0;
8 }
9 for (int e = 0; e < (int)cost.size(); e++) {
10 int a = original[e] - 'a', b = changed[e] - 'a';
11 dist[a][b] = min(dist[a][b], (long long)cost[e]);
12 }
13 for (int k = 0; k < 26; k++) {
14 for (int i = 0; i < 26; i++) {
15 if (dist[i][k] == INF) continue;
16 for (int j = 0; j < 26; j++) {
17 if (dist[i][k] + dist[k][j] < dist[i][j]) {
18 dist[i][j] = dist[i][k] + dist[k][j];
19 }
20 }
21 }
22 }
23 long long total = 0;
24 for (int p = 0; p < (int)source.size(); p++) {
25 long long d = dist[source[p] - 'a'][target[p] - 'a'];
26 if (d == INF) return -1;
27 total += d;
28 }
29 return total;
30 }
31};Time and space complexity
O(26^3 + m + n)
Floyd-Warshall over 26 letters is a constant 17,576 relaxations, loading rules is O(m), and summing is O(n).
O(26^2)
Only the 26 x 26 distance table is stored.
Other approaches
Dijkstra from each letter (time O(26 * m log 26 + n), space O(26^2 + m))
Run Dijkstra from each of the 26 letters (or only from letters that appear in source). It gives the same table and is a good choice when the alphabet is large, but Floyd-Warshall is shorter here.
Shortest path per position (time O(n * m log 26), space O(m))
Run a fresh search for every position. It recomputes the same few hundred pairs up to 10^5 times and is far too slow.
Common mistakes
- Keeping the last rule for a repeated pair instead of the cheapest one.
- Summing in a 32-bit integer. A path can cost about 2.5 * 10^7 and there can be 10^5 positions, so the total needs 64 bits.
- Using
INT_MAXorLong.MAX_VALUEas infinity and then adding two of them, which overflows. Use a smaller sentinel likeMAX / 4or skip infinite pivots. - Putting the pivot loop
kinside theiandjloops. Floyd-Warshall needskoutermost.
Frequently asked questions
Why not just use the direct rule between two letters?
A chain can be cheaper. In Example 1, c to b costs 5 directly but only 3 through e. Shortest paths capture every such chain.
Why is Floyd-Warshall fast enough?
Its cost depends only on the number of nodes, and there are exactly 26 letters. That is about 17,600 relaxations no matter how long the strings or how many rules there are.
Does the order of conversions at different positions matter?
No. Each rule changes one character at one position, so positions are independent and the minimum total is the sum of per-position minimums.
What if source[p] already equals target[p]?
The diagonal of the table is 0, so that position adds nothing.