Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Minimum Cost to Convert String I

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2976" 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 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]. 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 the string "abcd" to string "acbe": - Change value at index 1 from 'b' to 'c' at a cost of 5. - Change value at index 2 from 'c' to 'e' at a cost of 1. - Change value at index 2 from 'e' to 'b' at a cost of 2. - Change value at index 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 = "aaaa", target = "bbbb", original = ["a","c"], changed = ["c","b"], cost = [1,2] Output: 12 Explanation: 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. Example 3: Input: source = "abcd", target = "abce", original = ["a"], changed = ["e"], cost = [10000] Output: -1 Explanation: It is impossible to convert source to target because the value at index 3 cannot be changed from 'd' to 'e'. Constraints: 1 <= source.length == target.length <= 105 source, target consist of lowercase English letters. 1 <= cost.length == original.length == changed.length <= 2000 original[i], changed[i] are lowercase English letters. 1 <= cost[i] <= 106 original[i] != changed[i]

Explanation

Here's a breakdown of the solution:

  • Dijkstra's Algorithm: For each character in the source string, we use Dijkstra's algorithm (or Floyd-Warshall since the number of characters is small) to find the minimum cost to convert it to the corresponding character in the target string.
  • Cost Matrix: We create a cost matrix representing the cost of converting one character to another. Initially, the cost of converting a character to itself is 0, and the cost between other characters is infinity (or a large number). The input original, changed, and cost arrays are used to populate this cost matrix.
  • Impossibility: If, for any character in the source string, the minimum cost to convert it to the corresponding character in the target string is infinity, it means it's impossible to perform the conversion, and we return -1.

  • Runtime Complexity: O(n * m^2) where n is the length of the source string and m is the number of characters (26). Floyd-Warshall is O(m^3) and it's called n times, so O(n*m^3), but since m is limited to 26, this is roughly O(n).

  • Storage Complexity: O(m^2), due to the cost matrix.

Code

    def minimumCost(source: str, target: str, original: list[str], changed: list[str], cost: list[int]) -> int:
    """
    Calculates the minimum cost to convert source to target.

    Args:
        source: The source string.
        target: The target string.
        original: The list of original characters.
        changed: The list of changed characters.
        cost: The list of costs.

    Returns:
        The minimum cost to convert source to target, or -1 if impossible.
    """

    n = len(source)
    if n != len(target):
        return -1

    m = 26  # Number of lowercase English letters
    cost_matrix = [[float('inf')] * m for _ in range(m)]

    for i in range(m):
        cost_matrix[i][i] = 0  # Cost to convert to itself is 0

    for i in range(len(original)):
        u = ord(original[i]) - ord('a')
        v = ord(changed[i]) - ord('a')
        cost_matrix[u][v] = min(cost_matrix[u][v], cost[i])  # Use min in case of duplicates

    # Floyd-Warshall algorithm to find shortest paths between all pairs of characters
    for k in range(m):
        for i in range(m):
            for j in range(m):
                cost_matrix[i][j] = min(cost_matrix[i][j], cost_matrix[i][k] + cost_matrix[k][j])

    total_cost = 0
    for i in range(n):
        u = ord(source[i]) - ord('a')
        v = ord(target[i]) - ord('a')
        if cost_matrix[u][v] == float('inf'):
            return -1  # Impossible to convert
        total_cost += cost_matrix[u][v]

    return total_cost

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Minimum Cost to Convert String I