Construct String with Minimum Cost - Problem
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.
Input & Output
Example 1 — Single Word Match
$
Input:
target = "abc", words = ["ab","abc","a","c"], costs = [2,1,3,1]
›
Output:
1
💡 Note:
Use word "abc" with cost 1 to construct the entire target string directly.
Example 2 — Multiple Words
$
Input:
target = "abc", words = ["a","b","c"], costs = [1,1,1]
›
Output:
3
💡 Note:
Use "a" + "b" + "c" with total cost 1 + 1 + 1 = 3.
Example 3 — Impossible Case
$
Input:
target = "abc", words = ["ab","ac"], costs = [1,1]
›
Output:
-1
💡 Note:
Cannot construct "abc" using only "ab" and "ac" - missing required characters.
Constraints
- 1 ≤ target.length ≤ 5 × 104
- 1 ≤ words.length ≤ 1000
- 1 ≤ words[i].length ≤ target.length
- 1 ≤ costs[i] ≤ 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Target string 'abc' and word options with costs
2
Process
Find minimum cost combination of words
3
Output
Return minimum cost or -1 if impossible
Key Takeaway
🎯 Key Insight: Use dynamic programming to find the minimum cost combination of words that can construct the target string.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code