Construct String with Minimum Cost Problem
Description
LeetCode Problem 3213.
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 <= 5 * 10^41 <= words.length == costs.length <= 5 * 10^41 <= words[i].length <= target.length- The total sum of
words[i].lengthis less than or equal to5 * 10^4. targetandwords[i]consist only of lowercase English letters.1 <= costs[i] <= 10^4
Solution
Approach: String Hashing + Dynamic Programming
Let f[i] be the minimum cost to build the first i characters of target. Start with f[0] = 0 and everything else infinite; the answer is f[n], where n is the length of target.
To compute f[i], try every distinct word length j <= i. Hash the segment target[i-j+1..i]; if some word has the same hash, we can move from f[i-j] to f[i] at the cheapest cost among the words with that hash:
f[i] = min(f[i], f[i - j] + cost)
The distinct word lengths are at most about sqrt(L), since their sum is at most L, the total length of all words. Rolling hashes with prefix hashes make each segment hash O(1).
Complexity: time O(n * sqrt(L)), space O(n), where n is the length of target and L is the total length of words.
from collections import defaultdict
from math import inf
class Solution:
def minimumCost(self, target: str, words: List[str], costs: List[int]) -> int:
base, mod = 13331, 998244353
n = len(target)
h = [0] * (n + 1)
p = [1] * (n + 1)
for i, c in enumerate(target, 1):
h[i] = (h[i - 1] * base + ord(c)) % mod
p[i] = (p[i - 1] * base) % mod
f = [0] + [inf] * n
ss = sorted(set(map(len, words)))
d = defaultdict(lambda: inf)
min = lambda a, b: a if a < b else b
for w, c in zip(words, costs):
x = 0
for ch in w:
x = (x * base + ord(ch)) % mod
d[x] = min(d[x], c)
for i in range(1, n + 1):
for j in ss:
if j > i:
break
x = (h[i] - h[i - j] * p[j]) % mod
f[i] = min(f[i], f[i - j] + d[x])
return f[n] if f[n] < inf else -1