Skip to main content

Text Justification

HardPremium

Given an array of words and a width max_width, format the text so that every line has exactly max_width characters and is fully justified. Return the lines as a list of strings.

Follow these rules:

  • Pack each line greedily: fit as many words as possible, with at least one space between neighbors.
  • Spread the extra spaces between the words as evenly as possible. When they don't divide evenly, the gaps on the left get one more space than the gaps on the right.
  • A line with a single word is left-justified: the word, then spaces to fill the width.
  • The last line is left-justified too: single spaces between words, then spaces to fill the width.

Example 1

Input: words = ["Keep", "the", "spacing", "even", "between", "words", "on", "each", "line."], max_width = 16 Output: [ "Keep the spacing", "even between", "words on each", "line. " ]

The third line has 5 spaces to share between 2 gaps, so the left gap gets 3 and the right gap gets 2. The last line is left-justified.

Example 2

Input: words = ["Short", "lines", "end", "here."], max_width = 11 Output: [ "Short lines", "end here. " ]

Constraints

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • words[i].length <= max_width <= 100
  • Each word contains only non-space characters.