Solving Leetcode Interviews in Seconds with AI: Minimum Cost to Convert String II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2977" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
You are given two 0-indexed strings source and target, both of length n and consisting of lowercase English characters. You are also given two 0-indexed string arrays original and changed, and an integer array cost, where cost[i] represents the cost of converting the string original[i] to the string changed[i]. You start with the string source. In one operation, you can pick a substring x from the string, and change it to y at a cost of z if there exists any index j such that cost[j] == z, original[j] == x, and changed[j] == y. You are allowed to do any number of operations, but any pair of operations must satisfy either of these two conditions: The substrings picked in the operations are source[a..b] and source[c..d] with either b < c or d < a. In other words, the indices picked in both operations are disjoint. The substrings picked in the operations are source[a..b] and source[c..d] with a == c and b == d. In other words, the indices picked in both operations are identical. 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]. Example 1: Input: 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] Output: 28 Explanation: To convert "abcd" to "acbe", do the following operations: - Change substring source[1..1] from "b" to "c" at a cost of 5. - Change substring source[2..2] from "c" to "e" at a cost of 1. - Change substring source[2..2] from "e" to "b" at a cost of 2. - Change substring source[3..3] from "d" to "e" at a cost of 20. The total cost incurred is 5 + 1 + 2 + 20 = 28. It can be shown that this is the minimum possible cost. Example 2: Input: source = "abcdefgh", target = "acdeeghh", original = ["bcd","fgh","thh"], changed = ["cde","thh","ghh"], cost = [1,3,5] Output: 9 Explanation: To convert "abcdefgh" to "acdeeghh", do the following operations: - Change substring source[1..3] from "bcd" to "cde" at a cost of 1. - Change substring source[5..7] from "fgh" to "thh" at a cost of 3. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation. - Change substring source[5..7] from "thh" to "ghh" at a cost of 5. We can do this operation because indices [5,7] are disjoint with indices picked in the first operation, and identical with indices picked in the second operation. The total cost incurred is 1 + 3 + 5 = 9. It can be shown that this is the minimum possible cost. Example 3: Input: source = "abcdefgh", target = "addddddd", original = ["bcd","defgh"], changed = ["ddd","ddddd"], cost = [100,1578] Output: -1 Explanation: It is impossible to convert "abcdefgh" to "addddddd". If you select substring source[1..3] as the first operation to change "abcdefgh" to "adddefgh", you cannot select substring source[3..7] as the second operation because it has a common index, 3, with the first operation. If you select substring source[3..7] as the first operation to change "abcdefgh" to "abcddddd", you cannot select substring source[1..3] as the second operation because it has a common index, 3, with the first operation. Constraints: 1 <= source.length == target.length <= 1000 source, target consist only of lowercase English characters. 1 <= cost.length == original.length == changed.length <= 100 1 <= original[i].length == changed[i].length <= source.length original[i], changed[i] consist only of lowercase English characters. original[i] != changed[i] 1 <= cost[i] <= 106
Explanation
Here's a breakdown of the solution and the Python code:
Key Idea: The problem can be solved using dynamic programming.
dp[i]stores the minimum cost to convertsource[:i]totarget[:i]. For each indexi, we iterate backward fromj = idown to 0, considering all possible substrings ending ati. If we can convertsource[j:i]totarget[j:i]using a given conversion, we updatedp[i]by consideringdp[j]+ cost of conversion.Base Case:
dp[0] = 0(empty string needs no conversion).Optimization: Use memoization in the form of dynamic programming, building up the solution from subproblems.
Complexity:
- Runtime: O(n^3 * m), where n is the length of the source string and m is the number of conversion rules.
- Storage: O(n), where n is the length of the source string.
Code
def min_cost_to_convert(source: str, target: str, original: list[str], changed: list[str], cost: list[int]) -> int:
"""
Calculates the minimum cost to convert the source string to the target string.
Args:
source: The source string.
target: The target string.
original: A list of strings representing the original substrings.
changed: A list of strings representing the changed substrings.
cost: A list of integers representing the cost of each conversion.
Returns:
The minimum cost to convert the source string to the target string, or -1 if it is impossible.
"""
n = len(source)
dp = [float('inf')] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
dp[i] = dp[i - 1] + (0 if source[i-1] == target[i-1] else float('inf'))
if dp[i] == float('inf'):
dp[i] = float('inf')
for j in range(i):
sub_source = source[j:i]
sub_target = target[j:i]
for k in range(len(original)):
if original[k] == sub_source and changed[k] == sub_target:
if dp[j] != float('inf'):
dp[i] = min(dp[i], dp[j] + cost[k])
if dp[n] == float('inf'):
return -1
else:
return dp[n]