Construct String with Minimum Cost (Easy) Problem
Description
LeetCode Problem 3253.
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
iin the range[0, words.length - 1]. - Append
words[i]tos. - 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 <= 20001 <= words.length == costs.length <= 501 <= words[i].length <= target.lengthtargetandwords[i]consist only of lowercase English letters.1 <= costs[i] <= 10^5
Solution
Approach: Trie + Memoized Search
Put all words in a trie. A node that ends a word stores the cheapest cost among the words that end there (duplicates may have different costs).
Let dfs(i) be the minimum cost to build target[i:], with dfs(n) = 0. From position i, walk down the trie along target[i], target[i+1], .... Whenever the current node ends a word that was inserted, say at position j, we can append it and pay its cost plus dfs(j + 1). Stop as soon as the trie has no matching child. Cache the results per i. If dfs(0) is still infinite, return -1.
Complexity: O(n^2 + L) time and O(n + L) space, where n is the length of target and L is the total length of the words.
from functools import lru_cache
from math import inf
class Trie:
def __init__(self):
self.children: List[Optional[Trie]] = [None] * 26
self.cost = inf
def insert(self, word: str, cost: int):
node = self
for c in word:
idx = ord(c) - ord("a")
if node.children[idx] is None:
node.children[idx] = Trie()
node = node.children[idx]
node.cost = min(node.cost, cost)
class Solution:
def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:
@lru_cache(None)
def dfs(i: int) -> int:
if i >= len(target):
return 0
ans = inf
node = trie
for j in range(i, len(target)):
idx = ord(target[j]) - ord("a")
if node.children[idx] is None:
return ans
node = node.children[idx]
ans = min(ans, node.cost + dfs(j + 1))
return ans
trie = Trie()
for word, cost in zip(words, costs):
trie.insert(word, cost)
ans = dfs(0)
return ans if ans < inf else -1