FunctionRacerProblemsRace

Justify Lines to Width

HardStringsPython, JavaScript, TypeScript, Java, C++

words is a list of words and width is a line width; no word is longer than width. Lay the words out on lines in order, greedily: a line keeps taking the next word as long as the line still fits, where a line with m words fits when the lengths of its words plus m - 1 single spaces total at most width.

Then pad every line to exactly width characters:

Return the list of lines. When all the words fit on one line, that line is the last line.

Example 1

words ["this","is","an","example","of","text","justification."]
width 16
returns ["this is an","example of text","justification. "]

this is an has 8 letters and needs 8 spaces over 2 gaps, 4 each; example of text has 13 letters and 3 spaces over 2 gaps, so the left gap gets 2; the last line is padded on the right.

Example 2

words ["what","must","be","acknowledgment","shall","be"]
width 16
returns ["what must be","acknowledgment ","shall be "]

what must be fills 16 with 3 extra spaces over 2 gaps, so the left gap gets one more; acknowledgment is alone on its line and the spaces go after it; shall be is the last line.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Strings problems