Optimal Paragraph Formatting - Problem

You are tasked with formatting a paragraph where each character has a variable width. Given a list of words and their character widths, format them into lines with a maximum width constraint to minimize the total raggedness across all lines.

The raggedness of a line is defined as the cube of the number of extra spaces at the end of the line. The goal is to minimize the sum of raggedness across all lines in the paragraph.

Each word must fit entirely on a line (cannot be split), and there must be at least one space between words on the same line. The last line has zero raggedness regardless of trailing spaces.

Input:

  • words: Array of strings representing the words
  • widths: Array of integers where widths[i] represents the total character width of words[i]
  • maxWidth: Maximum allowed width per line

Output:

  • Return the minimum total raggedness possible

Input & Output

Example 1 — Basic Paragraph
$ Input: words = ["Hello", "World", "This", "Test"], widths = [5, 5, 4, 4], maxWidth = 12
Output: 125
💡 Note: Optimal formatting: Line 1: 'Hello World' (width=11, raggedness=1³=1), Line 2: 'This Test' (width=9, raggedness=(12-9)³=27), Last line has no raggedness. Total: 1 + 27 = 28. Wait, let me recalculate: Better formatting might be 'Hello' alone (raggedness=7³=343) then 'World This Test' (width=14 > 12, invalid). Actually 'Hello World' + 'This Test' gives 1 + 27 = 28 as minimum.
Example 2 — Single Line
$ Input: words = ["Hi", "There"], widths = [2, 5], maxWidth = 10
Output: 0
💡 Note: Both words fit on one line: 'Hi There' has width 2+1+5=8 ≤ 10. Since this is the last (and only) line, raggedness = 0.
Example 3 — Forced Splits
$ Input: words = ["A", "B", "C"], widths = [1, 1, 1], maxWidth = 2
Output: 2
💡 Note: Each word must be on its own line due to width constraint. Line 1: 'A' (raggedness=1³=1), Line 2: 'B' (raggedness=1³=1), Line 3: 'C' (last line, no raggedness). Total: 1 + 1 = 2.

Constraints

  • 1 ≤ words.length ≤ 100
  • 1 ≤ words[i].length ≤ 20
  • widths[i] > 0
  • 1 ≤ maxWidth ≤ 100
  • Each word must fit within maxWidth

Visualization

Tap to expand
INPUTALGORITHMRESULTHelloWorldThisTestw=5w=5w=4w=4Max Width: 121Try all line breaks2Calculate raggedness3Use DP to find minimum4Build from subproblemsLine 1: Hello WorldLine 2: This TestRaggedness: 1³ + 3³ = 28Total Cost: 28Key Insight:Dynamic programming finds optimal line breaks by building solutionsfrom smaller subproblems, minimizing total raggedness efficiently.TutorialsPoint - Optimal Paragraph Formatting | Bottom-Up Dynamic Programming
Asked in
Google 35 Microsoft 28 Amazon 22 Adobe 18
23.4K Views
Medium Frequency
~35 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