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 Cost INPUT target: "abcdef" words[]: abdef abc d def ef costs[]: 100 1 1 10 5 Build target from words: a b c d e f 0 1 2 3 4 5 Goal: Find minimum cost to construct "abcdef" using words with costs Approach: Dynamic Programming ALGORITHM STEPS 1 Initialize DP array dp[i] = min cost for target[0..i] dp: [0, inf, inf, inf, inf, inf, inf] 2 Try "abc" at pos 0 Matches! dp[3] = 0+1 = 1 3 Try "d" at pos 3 Matches! dp[4] = 1+1 = 2 4 Try "ef" at pos 4 Matches! dp[6] = 2+5 = 7 Final DP Table: pos: 0 1 2 3 4 5 6 dp: 0 - - 1 2 - 7 (-) means infinity Optimal: "abc"(1) + "d"(1) + "ef"(5) Total Cost: 1 + 1 + 5 = 7 FINAL RESULT Constructed String: abc cost: 1 + d cost: 1 + ef cost: 5 = "abcdef" Output: 7 OK - Minimum cost found! 1 + 1 + 5 = 7 (abc + d + ef) Key Insight: Use DP where dp[i] represents minimum cost to build target[0..i-1]. For each position, try all words that match starting at that position. Transition: dp[i + len(word)] = min(dp[i + len(word)], dp[i] + cost). Time: O(n * m * L) where n=target length, m=words count, L=max word length. Use Trie for optimization. TutorialsPoint - Construct String with Minimum Cost (Easy) | Dynamic Programming Approach
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