Ctrl K

Word Wrap With a Slack Penalty

Medium
You get a text text (words of lowercase English letters separated by single spaces) and a line width width. Break the text into rows by inserting line breaks between words: - words cannot be split or reordered; - neighbouring words on a row are separated by exactly one space, with no leading or trailing spaces; - every row is at most width characters long. A row of length len has a penalty of (width − len)². The penalty of the whole layout is the sum over all rows **except the last one**. Return the smallest possible penalty.
Example 1
text="we ship code daily", width=8 → 17

The best split is "we ship" (7 characters, penalty (8 − 7)² = 1), then "code" ((8 − 4)² = 16), and the last row "daily" is free. Total 17.

Example 2
text="tiny note", width=20 → 0

The whole text fits on one row, and the last row carries no penalty.

Example 3
text="aa bb cc", width=5 → 0
Constraints
  • 1 ≤ len(text) ≤ 5000
  • 1 ≤ width ≤ 5000
  • text consists of lowercase English letters and spaces, does not start or end with a space, and words are separated by single spaces
  • No word is longer than width
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsFewest Jumps to the End MediumMost Profitable Streak MediumReach the Last Cell MediumWarehouse Cart Routes MediumCheapest Corner-to-Corner Route Medium
loading Python…
Input
text="we ship code daily", width=8
Expected
17

Run checks the first 3 tests in your browser. Submit checks all 85 tests on the server, hidden ones included.