Construct String with Minimum Cost (Easy) - 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 — Basic Case
$ Input: target = "abcdef", words = ["abdef","abc","d","def","ef"], costs = [100,1,1,10,5]
Output: 7
💡 Note: The minimum cost is achieved by: "abc" (cost 1) + "d" (cost 1) + "ef" (cost 5) = 7
Example 2 — Impossible Case
$ Input: target = "aaaa", words = ["z","zz","zzz"], costs = [1,10,100]
Output: -1
💡 Note: It's impossible to construct "aaaa" using words that only contain 'z'
Example 3 — Single Word Match
$ Input: target = "abc", words = ["abc"], costs = [5]
Output: 5
💡 Note: Use the single word "abc" with cost 5 to match the entire target

Constraints

  • 1 ≤ target.length ≤ 5 × 104
  • 1 ≤ words.length ≤ 1000
  • 1 ≤ words[i].length ≤ 5 × 104
  • 1 ≤ costs[i] ≤ 104

Visualization

Tap to expand
Construct String with Minimum CostTarget: "abcdef"a b c d e fAvailable Words:"abdef" (100)"abc" (1)"d" (1)"def" (10)"ef" (5)Optimal Solution:"abc"+"d"+"ef"Total Cost: 1 + 1 + 5 = 7
Understanding the Visualization
1
Input
Target string "abcdef" and available words with costs
2
Process
Find optimal combination of words to build target
3
Output
Return minimum total 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
34.6K Views
Medium Frequency
~25 min Avg. Time
892 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