Minimum Cost to Separate Sentence Into Rows - Problem

You are given a string sentence containing words separated by spaces, and an integer k. Your task is to separate sentence into rows where the number of characters in each row is at most k.

You may assume that sentence does not begin or end with a space, and the words in sentence are separated by a single space. You can split sentence into rows by inserting line breaks between words in sentence. A word cannot be split between two rows. Each word must be used exactly once, and the word order cannot be rearranged.

Adjacent words in a row should be separated by a single space, and rows should not begin or end with spaces. The cost of a row with length n is (k - n)², and the total cost is the sum of the costs for all rows except the last one.

Example: If sentence = "i love leetcode" and k = 12:
• Separating sentence into "i", "love", and "leetcode" has a cost of (12 - 1)² + (12 - 4)² = 121 + 64 = 185
• Separating sentence into "i love", and "leetcode" has a cost of (12 - 6)² = 36

Return the minimum possible total cost of separating sentence into rows.

Input & Output

Example 1 — Basic Case
$ Input: sentence = "i love leetcode", k = 12
Output: 36
💡 Note: Split into "i love" (6 chars) and "leetcode" (8 chars). Cost = (12-6)² = 36. Last row has no cost.
Example 2 — Single Word Per Row
$ Input: sentence = "hello world", k = 8
Output: 25
💡 Note: Split into "hello" (5 chars) and "world" (5 chars). Cost = (8-5)² = 9. Wait, "hello world" = 11 chars > 8, so must split. Cost = (8-5)² = 9.
Example 3 — All Words Fit
$ Input: sentence = "a b c", k = 10
Output: 0
💡 Note: All words fit in one row: "a b c" (5 chars ≤ 10). Since it's the last (and only) row, cost = 0.

Constraints

  • 1 ≤ sentence.length ≤ 500
  • 1 ≤ k ≤ 500
  • sentence consists of only lowercase English letters and spaces
  • sentence does not start or end with a space
  • Words in sentence are separated by a single space

Visualization

Tap to expand
Minimum Cost Text Wrapping: "i love leetcode" with k=12Original: "i love leetcode"Need to split into rows ≤ 12 characters"i love" (6)"leetcode" (8)Cost = (12-6)² + 0 = 36"i" (1)"love" (4)"leetcode" (8)Cost = (12-1)² + (12-4)² + 0 = 185Optimal SolutionMinimum Cost: 36
Understanding the Visualization
1
Input
sentence = "i love leetcode", k = 12
2
Split Options
Try different ways to break into rows
3
Calculate Cost
Cost = (k - length)² for each row except last
Key Takeaway
🎯 Key Insight: Use dynamic programming to find optimal split points that minimize total cost
Asked in
Google 15 Microsoft 12 Amazon 8
21.0K 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