You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# [Problem 2976: Minimum Cost to Convert String I](https://leetcode.com/problems/minimum-cost-to-convert-string-i/description/?envType=daily-question)
2
2
3
3
## Initial thoughts (stream-of-consciousness)
4
-
We need to transform source -> target by repeatedly applying character substitutions that are allowed by given (original -> changed) operations with associated costs. Each operation changes a single character at some cost; operations can be chained (e.g., a -> c then c -> b). For a single position, the minimal cost to change letter x to y is just the shortestpath cost from x to y in a directed weighted graph where nodes are letters and edges are given substitutions. Because substitutions are independent per character position, total cost is the sum of minimal per-position costs. If any required conversion is impossible (no path), answer is -1.
4
+
We need to convert each character of source to the corresponding character in target. Each allowed operation is changing a single character x -> y at a given cost z if such an operation exists in the input arrays. Because we can apply operations any number of times and in any sequence, this is naturally a shortest-path problem on a directed graph of letters (26 nodes a..z). Each given (original[i] -> changed[i]) with cost[i] is a directed edge; repeated operations correspond to following a path.
5
5
6
-
This suggests building a graph on 26 lowercase letters and computing shortest paths between all pairs; since alphabet size is small (26), Floyd-Warshall is appropriate and simple. Alternative: run Dijkstra from each source letter encountered, but Floyd-Warshall is easy and fast enough.
6
+
So for each position where source[i] != target[i], we need the minimum path cost from source[i] to target[i] in that directed graph. If any required pair is unreachable, return -1. Sum the minimal costs over positions. Build a 26x26 distance matrix, initialize with +inf except zeros on diagonal, set direct edge costs to the minimum among duplicates, then run Floyd–Warshall (26^3 is tiny). Finally sum distances for each mismatch.
7
+
8
+
Potential pitfalls: directed edges (not undirected), multiple edges between same pair, large n so summation must be efficient, detect unreachable pairs.
7
9
8
10
## Refining the problem, round 2 thoughts
9
-
- Build a 26x26 distance matrix, initialize distances to INF, dist[i][i] = 0.
10
-
- For each given original[i] -> changed[i] with cost[i], set dist[u][v] = min(dist[u][v], cost[i]) because multiple edges may be present.
11
-
- Run Floyd-Warshall to get minimal costs between all letter pairs.
12
-
- Iterate positions of source/target: if source[i] == target[i], cost 0; else if dist[src][tgt] is INF -> return -1; otherwise add dist[src][tgt].
13
-
- Time complexity: O(26^3) for Floyd-Warshall (~17k operations) + O(n) to sum costs. Space O(26^2).
14
-
- Use a sufficiently large INF (e.g., 10**18) to avoid overflow.
Floyd–Warshall is simplest and safe: 26 nodes -> 26^3 ~ 17576 iterations. Alternatively could run Dijkstra from each source letter that appears in source where it differs from target — still cheap but more bookkeeping. Use Floyd–Warshall for clarity.
12
+
13
+
Edge cases:
14
+
- If source[i] == target[i] cost is 0.
15
+
- If there is no path from source[i] to target[i], answer is -1.
16
+
- There may be multiple edges between same nodes; pick the smallest.
17
+
- Costs can be up to 1e6 and n up to 1e5, so total sum can be large but fits Python int.
18
+
Time complexity: O(26^3 + n) ~ O(1 + n) effectively; space O(26^2).
# Quick length check (given by problem they are equal)
27
+
# Quick length check (problem guarantees same length)
25
28
if n !=len(target):
26
29
return-1
27
30
28
-
ALPH=26
29
31
INF=10**18
30
-
# dist[a][b] = minimum cost to convert letter a -> b
31
-
dist = [[INF] *ALPHfor _ inrange(ALPH)]
32
-
for i inrange(ALPH):
32
+
# 26 letters
33
+
m =26
34
+
# dist[i][j] = min cost to convert chr(i+'a') -> chr(j+'a')
35
+
dist = [[INF] * m for _ inrange(m)]
36
+
for i inrange(m):
33
37
dist[i][i] =0
34
38
35
-
# Populate edges (take min if multiple edges between same pair)
36
-
m =len(cost)
37
-
for i inrange(m):
38
-
u =ord(original[i]) -ord('a')
39
-
v =ord(changed[i]) -ord('a')
40
-
if cost[i] < dist[u][v]:
41
-
dist[u][v] = cost[i]
39
+
# Populate direct edges (take min if multiple edges)
40
+
for o, c, w inzip(original, changed, cost):
41
+
u =ord(o) -ord('a')
42
+
v =ord(c) -ord('a')
43
+
if w < dist[u][v]:
44
+
dist[u][v] = w
42
45
43
-
# Floyd-Warshall
44
-
for k inrange(ALPH):
46
+
# Floyd-Warshall to get all-pairs shortest paths
47
+
for k inrange(m):
45
48
dk = dist[k]
46
-
for i inrange(ALPH):
49
+
for i inrange(m):
47
50
di = dist[i]
48
-
#small micro-optimization: if di[k] is INF skip inner
51
+
#minor micro-optimization: only proceed if di[k] not INF
49
52
ik = di[k]
50
53
if ik ==INF:
51
54
continue
52
55
# iterate j
53
-
# use local references
54
-
for j inrange(ALPH):
55
-
# if dk[j] == INF skip
56
-
val = ik + dk[j]
57
-
if val < di[j]:
58
-
di[j] = val
56
+
# Use local variables for speed
57
+
for j inrange(m):
58
+
nj = ik + dk[j]
59
+
if nj < di[j]:
60
+
di[j] = nj
59
61
62
+
# Sum up costs for each position
60
63
total =0
61
64
for i inrange(n):
62
-
a=ord(source[i]) -ord('a')
63
-
b=ord(target[i]) -ord('a')
64
-
ifa==b:
65
+
s= source[i]
66
+
t= target[i]
67
+
ifs==t:
65
68
continue
66
-
if dist[a][b] ==INF:
69
+
u =ord(s) -ord('a')
70
+
v =ord(t) -ord('a')
71
+
if dist[u][v] ==INF:
67
72
return-1
68
-
total += dist[a][b]
73
+
total += dist[u][v]
69
74
return total
70
75
```
71
-
- Approach: Model characters as nodes in a directed weighted graph; compute all-pairs shortest paths with Floyd-Warshall; sum minimal per-position costs, returning -1 if any required conversion is unreachable.
72
-
- Time complexity: O(26^3 + n) = O(n) for large n (26^3 is constant ≈ 17k ops).
73
-
- Space complexity: O(26^2) = O(1) (constant).
74
-
- Implementation notes: multiple given conversions between same pair are reduced by taking the minimum cost edge; self-conversions cost 0; INF is chosen large to avoid overflow.
76
+
- Approach: Model characters as nodes of a directed weighted graph. Use Floyd–Warshall to compute the minimum conversion cost between any pair of letters, then sum costs for each differing position in source/target. If any required conversion is impossible, return -1.
77
+
- Time complexity: O(26^3 + n) = O(n) effectively, since 26^3 is constant ~17.5k.
78
+
- Space complexity: O(26^2) = O(1) constant.
79
+
- Implementation details: Use INF large enough to avoid overflow; pick min when multiple direct edges exist; Floyd–Warshall triple loop with a small optimization skipping i when dist[i][k] is INF.
0 commit comments