Minimum Cost String Partition - Problem

Given a string s and a dictionary wordDict containing a list of valid words with their associated costs, partition the string into valid dictionary words such that the total cost is minimized.

Each word in the dictionary has a cost associated with it. Your task is to find the minimum cost to partition the entire string using words from the dictionary.

Example:

If s = "leetcode" and wordDict = {"leet": 10, "code": 15, "le": 5, "et": 8, "co": 12, "de": 7}, then one possible partition is ["leet", "code"] with cost 10 + 15 = 25. Another partition is ["le", "et", "co", "de"] with cost 5 + 8 + 12 + 7 = 32. The minimum cost partition would be the first one.

Return the minimum cost to partition the string, or -1 if it's impossible to partition the string using dictionary words.

Input & Output

Example 1 — Basic Case
$ Input: s = "leetcode", wordDict = {"leet": 10, "code": 15, "leetcode": 30}
Output: 25
💡 Note: Partition into ["leet", "code"] with costs 10 + 15 = 25, which is better than using "leetcode" (cost 30)
Example 2 — Multiple Options
$ Input: s = "cats", wordDict = {"cat": 5, "cats": 10, "ca": 3, "ts": 4}
Output: 7
💡 Note: Partition into ["ca", "ts"] with costs 3 + 4 = 7, better than "cat" + "s" (impossible) or "cats" (10)
Example 3 — Impossible Case
$ Input: s = "hello", wordDict = {"he": 1, "lo": 2}
Output: -1
💡 Note: Cannot partition "hello" using available words "he" and "lo" - missing "ll" part

Constraints

  • 1 ≤ s.length ≤ 300
  • 1 ≤ wordDict.length ≤ 1000
  • 1 ≤ wordDict[i].length ≤ 20
  • 1 ≤ wordDict[i].cost ≤ 1000
  • All dictionary words are unique

Visualization

Tap to expand
INPUTALGORITHMRESULTleetcode"leetcode"Dictionary:"leet": 10"code": 15"leetcode": 30"le": 5"et": 8"co": 121Initialize DP array2Set dp[n] = 03Fill from right to left4Try all word endingsDP Array:25150dp[4] = min(code cost + dp[8])dp[0] = min(leet cost + dp[4])MinimumCost: 25Optimal partition:leetcode1015Total: 10 + 15 = 25Better than "leetcode"(cost 30)Key Insight:Dynamic programming builds the solution by considering all possible word boundaries,storing minimum costs for each position to avoid recalculating the same subproblems.TutorialsPoint - Minimum Cost String Partition | Bottom-Up Dynamic Programming
Asked in
Google 45 Amazon 38 Microsoft 29 Facebook 22
23.4K Views
Medium-High Frequency
~35 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