Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Construct String with Minimum Cost

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "3213" 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 a string target, an array of strings words, and an integer array costs, both arrays of the same length. Imagine an empty string s. You can perform the following operation any number of times (including zero): Choose an index i in the range [0, words.length - 1]. Append words[i] to s. The cost of operation is costs[i]. Return the minimum cost to make s equal to target. If it's not possible, return -1. Example 1: Input: target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5] Output: 7 Explanation: The minimum cost can be achieved by performing the following operations: Select index 1 and append "abc" to s at a cost of 1, resulting in s = "abc". Select index 2 and append "d" to s at a cost of 1, resulting in s = "abcd". Select index 4 and append "ef" to s at a cost of 5, resulting in s = "abcdef". Example 2: Input: target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100] Output: -1 Explanation: It is impossible to make s equal to target, so we return -1. Constraints: 1 <= target.length <= 5 104 1 <= words.length == costs.length <= 5 104 1 <= words[i].length <= target.length The total sum of words[i].length is less than or equal to 5 * 104. target and words[i] consist only of lowercase English letters. 1 <= costs[i] <= 104

Explanation

Here's a solution to the problem, addressing the requirements for efficiency, optimality, and clarity.

  • Dynamic Programming: Use dynamic programming to store the minimum cost to form prefixes of the target string. The state dp[i] represents the minimum cost to form the target string up to index i-1.

  • Iteration and Matching: Iterate through the target string and, for each position, try to match words from the input array. If a word matches a suffix of the current prefix, update the DP table with the minimum cost.

  • Initialization and Result: Initialize the DP table with infinity for all prefixes except the empty string (which has a cost of 0). The final result is the value in the DP table corresponding to the full target string.

  • Complexity: Time Complexity: O(m*n*k), where m is the length of the target, n is the number of words, and k is the maximum length of a word. Space Complexity: O(m), where m is the length of the target (due to the dp array).

Code

    def min_cost(target: str, words: list[str], costs: list[int]) -> int:
    """
    Calculates the minimum cost to form the target string by appending words.

    Args:
        target: The target string to form.
        words: The list of words that can be appended.
        costs: The cost associated with each word.

    Returns:
        The minimum cost to form the target string, or -1 if it's not possible.
    """

    n = len(target)
    dp = [float('inf')] * (n + 1)
    dp[0] = 0

    for i in range(1, n + 1):
        dp[i] = dp[i - 1] #init value, at worst case, we add each char

        for j in range(len(words)):
            word = words[j]
            cost = costs[j]
            word_len = len(word)

            if i >= word_len and target[i - word_len:i] == word:
                dp[i] = min(dp[i], dp[i - word_len] + cost)

    if dp[n] == float('inf'):
        return -1
    else:
        return dp[n]

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Construct String with Minimum Cost