{ "data": { "question": { "questionId": "3235", "questionFrontendId": "2976", "boundTopicId": null, "title": "Minimum Cost to Convert String I", "titleSlug": "minimum-cost-to-convert-string-i", "content": "

You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English letters. You are also given two 0-indexed character arrays original and changed, and an integer array cost, where cost[i] represents the cost of changing the character original[i] to the character changed[i].

\n\n

You start with the string source. In one operation, you can pick a character x from the string and change it to the character y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y.

\n\n

Return the minimum cost to convert the string source to the string target using any number of operations. If it is impossible to convert source to target, return -1.

\n\n

Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].

\n\n

 

\n

Example 1:

\n\n
\nInput: source = "abcd", target = "acbe", original = ["a","b","c","c","e","d"], changed = ["b","c","b","e","b","e"], cost = [2,5,5,1,2,20]\nOutput: 28\nExplanation: To convert the string "abcd" to string "acbe":\n- Change value at index 1 from 'b' to 'c' at a cost of 5.\n- Change value at index 2 from 'c' to 'e' at a cost of 1.\n- Change value at index 2 from 'e' to 'b' at a cost of 2.\n- Change value at index 3 from 'd' to 'e' at a cost of 20.\nThe total cost incurred is 5 + 1 + 2 + 20 = 28.\nIt can be shown that this is the minimum possible cost.\n
\n\n

Example 2:

\n\n
\nInput: source = "aaaa", target = "bbbb", original = ["a","c"], changed = ["c","b"], cost = [1,2]\nOutput: 12\nExplanation: To change the character 'a' to 'b' change the character 'a' to 'c' at a cost of 1, followed by changing the character 'c' to 'b' at a cost of 2, for a total cost of 1 + 2 = 3. To change all occurrences of 'a' to 'b', a total cost of 3 * 4 = 12 is incurred.\n
\n\n

Example 3:

\n\n
\nInput: source = "abcd", target = "abce", original = ["a"], changed = ["e"], cost = [10000]\nOutput: -1\nExplanation: It is impossible to convert source to target because the value at index 3 cannot be changed from 'd' to 'e'.\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Medium", "likes": 149, "dislikes": 5, "isLiked": null, "similarQuestions": "[{\"title\": \"Can Convert String in K Moves\", \"titleSlug\": \"can-convert-string-in-k-moves\", \"difficulty\": \"Medium\", \"translatedTitle\": null}, {\"title\": \"Minimum Moves to Convert String\", \"titleSlug\": \"minimum-moves-to-convert-string\", \"difficulty\": \"Easy\", \"translatedTitle\": null}]", "exampleTestcases": "\"abcd\"\n\"acbe\"\n[\"a\",\"b\",\"c\",\"c\",\"e\",\"d\"]\n[\"b\",\"c\",\"b\",\"e\",\"b\",\"e\"]\n[2,5,5,1,2,20]\n\"aaaa\"\n\"bbbb\"\n[\"a\",\"c\"]\n[\"c\",\"b\"]\n[1,2]\n\"abcd\"\n\"abce\"\n[\"a\"]\n[\"e\"]\n[10000]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class Solution {\npublic:\n long long minimumCost(string source, string target, vector& original, vector& changed, vector& cost) {\n \n }\n};", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class Solution {\n public long minimumCost(String source, String target, char[] original, char[] changed, int[] cost) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class Solution(object):\n def minimumCost(self, source, target, original, changed, cost):\n \"\"\"\n :type source: str\n :type target: str\n :type original: List[str]\n :type changed: List[str]\n :type cost: List[int]\n :rtype: int\n \"\"\"\n ", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class Solution:\n def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int:\n ", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "long long minimumCost(char* source, char* target, char* original, int originalSize, char* changed, int changedSize, int* cost, int costSize) {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class Solution {\n public long MinimumCost(string source, string target, char[] original, char[] changed, int[] cost) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {string} source\n * @param {string} target\n * @param {character[]} original\n * @param {character[]} changed\n * @param {number[]} cost\n * @return {number}\n */\nvar minimumCost = function(source, target, original, changed, cost) {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "function minimumCost(source: string, target: string, original: string[], changed: string[], cost: number[]): number {\n \n};", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class Solution {\n\n /**\n * @param String $source\n * @param String $target\n * @param String[] $original\n * @param String[] $changed\n * @param Integer[] $cost\n * @return Integer\n */\n function minimumCost($source, $target, $original, $changed, $cost) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "class Solution {\n func minimumCost(_ source: String, _ target: String, _ original: [Character], _ changed: [Character], _ cost: [Int]) -> Int {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class Solution {\n fun minimumCost(source: String, target: String, original: CharArray, changed: CharArray, cost: IntArray): Long {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Dart", "langSlug": "dart", "code": "class Solution {\n int minimumCost(String source, String target, List original, List changed, List cost) {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "func minimumCost(source string, target string, original []byte, changed []byte, cost []int) int64 {\n \n}", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "# @param {String} source\n# @param {String} target\n# @param {Character[]} original\n# @param {Character[]} changed\n# @param {Integer[]} cost\n# @return {Integer}\ndef minimum_cost(source, target, original, changed, cost)\n \nend", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "object Solution {\n def minimumCost(source: String, target: String, original: Array[Char], changed: Array[Char], cost: Array[Int]): Long = {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "impl Solution {\n pub fn minimum_cost(source: String, target: String, original: Vec, changed: Vec, cost: Vec) -> i64 {\n \n }\n}", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define/contract (minimum-cost source target original changed cost)\n (-> string? string? (listof char?) (listof char?) (listof exact-integer?) exact-integer?)\n )", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec minimum_cost(Source :: unicode:unicode_binary(), Target :: unicode:unicode_binary(), Original :: [char()], Changed :: [char()], Cost :: [integer()]) -> integer().\nminimum_cost(Source, Target, Original, Changed, Cost) ->\n .", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule Solution do\n @spec minimum_cost(source :: String.t, target :: String.t, original :: [char], changed :: [char], cost :: [integer]) :: integer\n def minimum_cost(source, target, original, changed, cost) do\n \n end\nend", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"8.5K\", \"totalSubmission\": \"22.9K\", \"totalAcceptedRaw\": 8525, \"totalSubmissionRaw\": 22917, \"acRate\": \"37.2%\"}", "hints": [ "Construct a graph with each letter as a node, and construct an edge (a, b) with weight c if we can change from character a to letter b with cost c. (Keep the one with the smallest cost in case there are multiple edges between a and b).", "Calculate the shortest path for each pair of characters (source[i], target[i]). The sum of cost over all i in the range [0, source.length - 1]. If there is no path between source[i] and target[i], the answer is -1.", "Any shortest path algorithms will work since we only have 26 nodes. Since we only have at most 26 * 26 pairs, we can save the result to avoid re-calculation.", "We can also use Floyd Warshall's algorithm to precompute all the results." ], "solution": null, "status": null, "sampleTestCase": "\"abcd\"\n\"acbe\"\n[\"a\",\"b\",\"c\",\"c\",\"e\",\"d\"]\n[\"b\",\"c\",\"b\",\"e\",\"b\",\"e\"]\n[2,5,5,1,2,20]", "metaData": "{\n \"name\": \"minimumCost\",\n \"params\": [\n {\n \"name\": \"source\",\n \"type\": \"string\"\n },\n {\n \"type\": \"string\",\n \"name\": \"target\"\n },\n {\n \"type\": \"character[]\",\n \"name\": \"original\"\n },\n {\n \"type\": \"character[]\",\n \"name\": \"changed\"\n },\n {\n \"type\": \"integer[]\",\n \"name\": \"cost\"\n }\n ],\n \"return\": {\n \"type\": \"long\"\n }\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 20 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 21. Using compile arguments: --enable-preview --release 21

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 11 using the gnu11 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 12 with .NET 8 runtime

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.2

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.9.

\"], \"golang\": [\"Go\", \"

Go 1.21

\\r\\n

Support https://godoc.org/github.com/emirpasic/gods@v1.18.1 library.

\"], \"python3\": [\"Python3\", \"

Python 3.11.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.9.0.

\\r\\n\\r\\n

We are using an experimental compiler provided by JetBrains.

\"], \"rust\": [\"Rust\", \"

Rust 1.74.1

\\r\\n\\r\\n

Supports rand v0.6\\u00a0from crates.io

\"], \"php\": [\"PHP\", \"

PHP 8.2.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 5.1.6, Node.js 16.13.2.

\\r\\n\\r\\n

Compile Options: --alwaysStrict --strictBindCallApply --strictFunctionTypes --target ES2022

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2022 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"], \"racket\": [\"Racket\", \"

Racket CS v8.11

\\r\\n\\r\\n

Using #lang racket

\\r\\n\\r\\n

Required data/gvector data/queue data/order data/heap automatically for your convenience

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 26\"], \"elixir\": [\"Elixir\", \"Elixir 1.15 with Erlang/OTP 26\"], \"dart\": [\"Dart\", \"

Dart 3.2

\\r\\n\\r\\n

Your code will be run directly without compiling

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }