Problem
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].
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.
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.
Note that there may exist indices i, j such that original[j] == original[i] and changed[j] == changed[i].
Examples
Example 1:
graph LR a -->|2| b d -->|20| e b -->|5| c c -->|5| b c -->|1| e e -->|2| b
| |
Example 2:
graph LR a -->|1| c c -->|2| b
| |
Example 3:
graph LR a -->|10000| e
| |
Constraint
source,targetconsist of lowercase English letters.1 <= cost[i] <= 10^6
Solution
Method 1 - Floyd Warshall Algorithm
To solve this problem, we need to find the minimum cost to convert the source string to the target string by transforming characters according to the given transformation rules defined by original, changed, and cost arrays.
Here’s a step-by-step plan to solve the problem:
- Create a Cost Matrix: Create a matrix representing the minimum cost to convert any character to any other character using given transformations. We’ll initialize it with a large value (to represent infinity) and update it based on the given transformations.
- Floyd-Warshall Algorithm for All-Pairs Shortest Path: Use the Floyd-Warshall algorithm to find the minimum cost to convert any character to any other character using possibly multiple transformations.
- Calculate Total Cost: Iterate through the
sourceandtargetstrings, and use the cost matrix to calculate the total cost of conversion. If any character conversion is not possible, return-1.
Video Explanation
Here is the video explanation of the same:
Code
| |
Complexity
- ⏰ Time complexity:
O(n)- Floyd Warshall algorithm takes
O(m^3)time, wheremis number of nodes in graph, and in this problem number of nodes can be 26, as only lower case letters are allowed. So, itO(26^3)=O(1) - Calculating the total cost using the distance matrix takes
O(n)time
- Floyd Warshall algorithm takes
- 🧺 Space complexity:
O(1)- The
conversionCostmatrix takesO(26^2)space, henceO(1)
- The