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 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.

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
Construct String with Minimum CostTarget: abcAvailable Words:ab (cost:2)abc (cost:1)a (cost:3)c (cost:1)Direct match!Options:• a + b + c = 3 + ? + 1 (impossible - no 'b')• ab + c = 2 + 1 = 3• abc = 1 ← minimum!Result: 1
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
23.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen