Minimum Cost to Separate Sentence Into Rows - Problem
Minimum Cost to Separate Sentence Into Rows

Imagine you're working on a text editor that needs to format sentences into multiple rows with optimal spacing. You have a sentence containing words separated by spaces and a maximum width k for each row.

Your task is to split the sentence into rows where:
• Each row has at most k characters
• Words cannot be broken across rows
• Word order must be preserved
• Adjacent words are separated by a single space

The cost of each row (except the last) is (k - length)², where length is the number of characters in that row. Your goal is to minimize the total cost.

Example: For sentence = "i love leetcode" and k = 12:
• Splitting into ["i"], ["love"], ["leetcode"] costs (12-1)² + (12-4)² = 121 + 64 = 185
• Splitting into ["i love"], ["leetcode"] costs (12-6)² = 36 ✓

Input & Output

example_1.py — Basic Case
$ Input: sentence = "i love leetcode", k = 12
Output: 36
💡 Note: We can separate into two rows: "i love" (length 6) and "leetcode" (length 8). Cost = (12-6)² = 36. The last row has no cost penalty.
example_2.py — Single Word Per Row
$ Input: sentence = "hello world", k = 6
Output: 25
💡 Note: Must separate into "hello" (length 5) and "world" (length 5). Cost = (6-5)² = 1 for first row. Wait, let me recalculate: "hello world" has length 11 > 6, so we need separate rows: cost = (6-5)² = 1.
example_3.py — Optimal vs Greedy
$ Input: sentence = "a b c d e", k = 5
Output: 4
💡 Note: Optimal: ["a b", "c d", "e"] with costs (5-3)² + (5-3)² = 4 + 0 = 4. Greedy ["a b c", "d e"] would give (5-5)² = 0, but "a b c" has length 5 exactly, so cost is 0 + 0 = 0. Actually optimal is ["a b c", "d e"] = 0.

Constraints

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

Visualization

Tap to expand
Text Formatting: Finding Optimal Line BreaksInput: "i love leetcode", k=12Option 1: Greedy (suboptimal)iempty (11 chars)Cost: (12-1)² = 121loveempty (8 chars)Cost: (12-4)² = 64leetcodeCost: 0 (last row)Total: 121 + 64 = 185Option 2: Optimal (DP solution)i loveempty (6)Cost: (12-6)² = 36leetcodeCost: 0 (last row)Total: 36DP finds optimal solution: 185 → 36 (80% reduction!)Key insight: Try all possible line endings and choose minimumdp[i] = min over all valid j of: (cost of line i to j) + dp[j+1]
Understanding the Visualization
1
Parse Words
Split the sentence into individual words and calculate their lengths
2
Try All Partitions
For each position, try different ways to end the current line
3
Calculate Penalties
Compute the squared penalty for each line based on unused space
4
Choose Optimal
Select the partitioning that gives minimum total penalty
Key Takeaway
🎯 Key Insight: Dynamic programming naturally finds the optimal partitioning by trying all possibilities and remembering the best solution for each subproblem, leading to significant cost reduction compared to greedy approaches.
Asked in
Google 45 Microsoft 38 Amazon 32 Meta 28
31.7K Views
Medium Frequency
~25 min Avg. Time
1.3K 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