Minimum total cost to convert one string into another using weighted character rules
MicrosoftSoftware Engineer · OtherLast updated
A string transformation problem: convert a source string into a target string using directed, weighted character replacement rules that may be chained at a position. It tests reasoning about multi-step conversions, choosing the cheapest of duplicate rules, detecting impossible positions, and totals beyond the 32-bit range.
You are given two strings, source and target, of the same length n, both made of lowercase English letters. You are also given a set of character conversion rules as three parallel lists original, changed and cost: rule j says that a single character equal to original[j] may be replaced by changed[j], and each such replacement costs cost[j].
You may apply rules any number of times, at any positions, in any order. Each application changes one character at one position and adds that rule's cost to the total. Return the minimum total cost needed to turn source into target, or -1 if it cannot be done.
Function Signature
def minimum_conversion_cost(source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int:
Rules
- Rules are directed: a rule from
atobdoes not allow changingbintoa. - Rules may be chained at one position: with a rule from
atocand another fromctob, a position holdingacan becomebby applying both and paying both costs. - Several rules may share the same
originalandchangedpair with different costs; any of them may be used. - A position where
sourceandtargetalready agree costs nothing. - If even one position cannot be converted, the answer is
-1.
Constraints
1 <= n <= 10^5andlen(source) == len(target) == n1 <= len(original) == len(changed) == len(cost) <= 2000- Every
original[j]andchanged[j]is a single lowercase English letter, andoriginal[j] != changed[j] 1 <= cost[j] <= 10^6- The answer can reach about
2.5 * 10^12, which exceeds2^31 - 1; it always fits within2^53, so return it as a plain integer.
Examples
Example 1
Input: source = "aab", target = "ccb", original = ["a", "b", "a"], changed = ["b", "c", "c"], cost = [1, 2, 5]
Output: 6
Changing a to c directly costs 5, but going from a to b and then from b to c costs 1 + 2 = 3. Positions 0 and 1 each cost 3, and position 2 already matches, so the total is 6.
Example 2
Input: source = "ab", target = "ba", original = ["a"], changed = ["b"], cost = [4]
Output: -1
Position 0 can become b for 4, but no rule or chain of rules turns b into a, so position 1 cannot be converted.
Example 3
Input: source = "ab", target = "bb", original = ["a", "a"], changed = ["b", "b"], cost = [7, 3]
Output: 3
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.