Skip to content

Text Justification

HardGreedy
Decode it first. Clues, constraints, pattern and plan before any code.

Lay out words as lines of text that are exactly width characters wide, and return the lines.

  • Fill lines one at a time and put as many words as fit on each line, with at least one space between neighbouring words.
  • Every line except the last is fully justified: pad the gaps between its words with spaces so the line reaches width. Spread the spaces as evenly as possible; if they do not divide evenly, gaps further left get one more than gaps to their right.
  • A line that holds a single word is the word followed by spaces.
  • The last line is left-aligned: one space between words, then spaces up to width.
words = ["Pack", "as", "many", "words", "as", "fit."], width = 15
 
"Pack   as  many"     (5 spaces over 2 gaps: 3 then 2)
"words as fit.  "     (last line: left-aligned)

Constraints

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • words[i].length <= width <= 100
  • No word contains a space.