Hard · Strings

Word wrap

Given an array of words and a width maxWidth, split the words, in order, into lines (words on a line joined by single spaces, each line at most maxWidth long) that minimize the sum of (maxWidth − line length)² over every line except the last, and return the lines; return null if any word is longer than maxWidth.

Examples

Example 1

["aaa","bb","cc","ddddd"] w=6

Output: ["aaa","bb cc","ddddd"]

Example 2

["a","b","c","d"] w=5

Output: ["a b c","d"]

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Strings problems