Skip to content
Decoder

Text Justification

Hard

Problem

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.

Example 1

words = ["Pack", "as", "many", "words", "as", "fit."], width = 15

Example 2

"Pack   as  many"     (5 spaces over 2 gaps: 3 then 2)

Example 3

"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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.