Cheapest Letter Rewrites with Directed Price Rules
Trees & GraphsAuto-graded · 23 test casesLast updated
Compute the minimum cost to rewrite one string into another with directed priced letter swaps, using shortest paths over 26 letters and handling impossible positions and large totals.
You have two lowercase strings, start and goal, of equal length. You also have a price list of single-letter rewrite rules, given as three parallel lists from_letters, to_letters and prices. Rule j lets you take one character equal to from_letters[j] and turn it into to_letters[j], paying prices[j] for that one rewrite.
You may use any rule any number of times, on any position, in any order. Every rewrite changes exactly one character at one position and adds the rule's price to your running total.
Return the smallest total price that transforms start into goal. If this is impossible, return -1.
Rules
- Rules are one-way. A rule from
xtoydoes not let you turnyintox. - Rewrites can be chained on the same position. If one rule turns
xintozand another turnszintoy, then a position holdingxcan becomeyby paying both prices. - The same
(from, to)pair may appear several times with different prices. You may use whichever one you like. - A position where
startandgoalalready hold the same letter costs nothing. - If at least one position cannot be converted, the answer is
-1.
Constraints
1 <= n <= 10^5, wheren = len(start) = len(goal)1 <= len(from_letters) = len(to_letters) = len(prices) <= 2000- Every entry of
from_lettersandto_lettersis one lowercase English letter, andfrom_letters[j] != to_letters[j] 1 <= prices[j] <= 10^6- The answer can be as large as about
2.5 * 10^12, beyond 32-bit range, but it fits in a 64-bit integer. Return it as a plain integer.
Examples
Example 1
Input: cheapest_rewrite_cost('aab', 'ccb', ['a', 'b', 'a'], ['b', 'c', 'c'], [1, 2, 5])
Output: 6
Example 2
Input: cheapest_rewrite_cost('ab', 'ba', ['a'], ['b'], [4])
Output: -1
Example 3
Input: cheapest_rewrite_cost('ab', 'bb', ['a', 'a'], ['b', 'b'], [7, 3])
Output: 3
Hints
Hint 1
Each rewrite touches a single position, so positions never interact. The total is the sum of independent per-position costs.
Hint 2
For one position, the cheapest conversion from letter a to letter b is a shortest path in a directed graph whose nodes are the 26 letters and whose edges are the rules.
Hint 3
With only 26 nodes, compute all-pairs shortest paths once (Floyd-Warshall, with the intermediate-letter loop outermost), keeping the cheapest of duplicate rules. Then answer each position by table lookup, returning -1 on an unreachable pair.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A rewrite changes one character at one position, so positions are independent. The answer is the sum, over all positions, of the cheapest way to turn start[i] into goal[i].
For a single position, think of a graph with 26 nodes (the letters). Each rule x -> y with price p is a directed edge of weight p. Applying a chain of rules is walking a path, so the cheapest conversion from letter a to letter b is the shortest-path distance from a to b.
Steps:
- Build a 26x26 matrix. Put
0on the diagonal and infinity elsewhere. For every rule, store the minimum price among rules with the same(from, to)pair. - Run Floyd-Warshall: for each intermediate letter
k(outermost loop), relaxdist[i][j]withdist[i][k] + dist[k][j]. - Count how many positions have each mismatched pair
(start[i], goal[i]). Matching positions cost nothing. - For each distinct pair, if its distance is infinite return
-1; otherwise adddistance * countto the total.
Why it is correct
- Independence: any sequence of rewrites splits into one sequence per position, so minimizing each position separately minimizes the total.
- Per-position optimality: a valid sequence at one position is a directed walk from the start letter to the goal letter, and its cost is the sum of edge weights. Weights are positive, so there are no negative cycles and Floyd-Warshall gives exact shortest distances.
- Duplicate rules: only the cheapest rule for a given pair can appear in an optimal path, so keeping the minimum is safe.
- Direction: the matrix is not symmetric, so a missing reverse path stays infinite and produces
-1. - Impossible position: if any required distance is infinite, the whole task is infeasible.
Complexity
Let n = len(start) and m = len(from_letters).
- Time:
O(n + m + 26^3), effectivelyO(n + m). - Space:
O(26^2), constant.
A shortest path uses at most 25 edges of at most 10^6 each, so one position costs at most 2.5 * 10^7 and the total stays near 2.5 * 10^12. Python integers handle this natively; in fixed-width languages use a 64-bit type.
Reference solution
from typing import List
def cheapest_rewrite_cost(start: str, goal: str, from_letters: List[str],
to_letters: List[str], prices: List[int]) -> int:
INF = float('inf')
# dist[i][j] = cheapest cost to turn letter i into letter j
dist = [[0 if i == j else INF for j in range(26)] for i in range(26)]
# Keep the cheapest among parallel rules
for a, b, c in zip(from_letters, to_letters, prices):
u, v = ord(a) - 97, ord(b) - 97
if c < dist[u][v]:
dist[u][v] = c
# Floyd-Warshall with k as the outermost loop
for k in range(26):
dk = dist[k]
for i in range(26):
dik = dist[i][k]
if dik == INF:
continue
di = dist[i]
for j in range(26):
if dik + dk[j] < di[j]:
di[j] = dik + dk[j]
# Count mismatched positions by (from, to) pair
pair_counts = {}
for a, b in zip(start, goal):
if a != b:
pair_counts[(a, b)] = pair_counts.get((a, b), 0) + 1
total = 0
for (a, b), cnt in pair_counts.items():
c = dist[ord(a) - 97][ord(b) - 97]
if c == INF:
return -1
total += c * cnt
return total