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 Cost INPUT target = "abc" a b c 0 1 2 words[] "ab" "abc" "a" "c" i=0 i=1 i=2 i=3 costs[] 2 1 3 1 Goal: Build "abc" using words with minimum cost "abc" matches target exactly! words[1] = "abc" ALGORITHM (DP) 1 Initialize DP dp[i] = min cost to build target[0..i-1] 0 INF INF INF "" "a" "ab" "abc" 2 For each position i Try all words that match target starting at i 3 Transition dp[i+len] = min(dp[i+len], dp[i] + cost[word]) At i=0: "abc" matches! dp[0+3] = min(INF, 0+1) = 1 Using words[1], cost=1 4 Return Result dp[target.length] or -1 if impossible 0 3 2 1 Answer! FINAL RESULT Optimal Solution Found Use word at index 1: "abc" Cost = 1 Building Process: s = "" (empty string) | + "abc" (cost: 1) v s = "abc" (matches target!) Output: 1 Other options: "a"+"b"+"c" not possible "ab"+"c" = 2+1 = 3 "a"+"bc" not possible Key Insight: Dynamic Programming with Trie optimization: Build target string character by character, tracking minimum cost at each position. For each position, try all words that match the suffix. Use Trie for O(1) lookup. Time: O(n * m * L) where n=target length, m=words count, L=max word length | Space: O(n + total chars) TutorialsPoint - Construct String with Minimum Cost | Dynamic Programming Approach
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