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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code