KatInterview

Cheapest Letter Rewrites with Directed Price Rules

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsgraphfloyd-warshallshortest-path

Last 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 x to y does not let you turn y into x.
  • Rewrites can be chained on the same position. If one rule turns x into z and another turns z into y, then a position holding x can become y by 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 start and goal already hold the same letter costs nothing.
  • If at least one position cannot be converted, the answer is -1.

Constraints

  • 1 <= n <= 10^5, where n = len(start) = len(goal)
  • 1 <= len(from_letters) = len(to_letters) = len(prices) <= 2000
  • Every entry of from_letters and to_letters is one lowercase English letter, and from_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.