Text Justification

Hard

Topics
ArrayStringSimulation

Given an array of words and a width maxWidth, format the text so that every line has exactly maxWidth characters and is both left and right justified.

Pack as many words onto a line as will fit, where words on a line are separated by at least one space. Then pad with spaces so the line is exactly maxWidth wide:

  • Spaces between words are distributed as evenly as possible. If they do not divide evenly, the left gaps take the extra space.
  • The last line is left justified instead: single spaces between words, then padding on the right.
  • A line holding one word is also left justified, padded on the right.

Return the list of lines.

The judge joins the returned lines with | so the trailing spaces on a line stay visible, since a line of text contains spaces of its own and could not otherwise be told apart from two lines.

Example 1

This····is····anexample··of·textjustification.··
a character of a worda space
These 7 words pack into 3 lines of exactly 16 characters each, which is what the fixed grid width shows. Words are taken in order and never split, so how many fit on a line is forced; the spaces are then what stretches the line to the full width. On the first line the gaps come out as 4 and 4, because the spare space is shared as evenly as it can be and any remainder goes to the left-hand gaps.
Spaces are drawn as cells because the number of them is the answer, not decoration.
Input:  words = ["This","is","an","example","of","text","justification."], maxWidth = 16
Output: ["This    is    an","example  of text","justification.  "]
Explanation: Line 1 holds 8 characters of words and 8 spare spaces over 2 gaps, which divides evenly into gaps of 4 and 4. Line 2 has 3 spare over 2 gaps, so the left gap takes the extra and the gaps are 2 and 1. The last line is left justified instead of stretched.

Example 2

What···must···beacknowledgment··shall·be········
a character of a worda space
Input:  words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
Output: ["What   must   be","acknowledgment  ","shall be        "]
Explanation: Line 2 holds one word, so it is left justified and padded right rather than stretched.

Example 3

a··
a character of a worda space
Every line here is either the last one or holds a single word, and those are left justified with the padding pushed to the right instead of being spread between words.
Input:  words = ["a"], maxWidth = 3
Output: ["a  "]
Explanation: A single word is the last line, so it is left justified and padded to the full width.

Constraints

  • 1 <= words.length <= 300
  • 1 <= words[i].length <= 20
  • 1 <= maxWidth <= 100
  • words[i].length <= maxWidth
Editorial — intuition, approach, complexity and pitfalls

Intuition

There is no insight to find here; the difficulty is entirely in the number of rules and the fact that three of them contradict the main one. This is a problem about reading the specification carefully and then not making an arithmetic slip.

Split it in two. First decide which words go on which line, which is purely a matter of capacity: a line can hold the next word if the words already on it, plus one space each, plus the new word, still fit. Then, separately, decide how to pad a line you have already chosen.

Keeping those two phases apart is what makes the code manageable, because the padding rule depends on facts the packing phase does not care about — whether the line is the last one, and whether it holds a single word.

The even-distribution arithmetic is the part most people get wrong. With gaps gaps and spare spaces to place, every gap gets spare / gaps and the first spare % gaps gaps get one extra. Writing it that way avoids a loop that dribbles spaces out one at a time and miscounts.

Approach

  1. Walk the words, accumulating a current line. Before adding a word, check whether width_so_far + len(line) + len(word) <= maxWidth, where len(line) is the number of single spaces already required.
  2. When a word does not fit, emit the current line and start a new one with that word.
  3. To emit a line that is not the last and holds more than one word: let gaps = len(line) - 1 and spare = maxWidth - total_word_length. Give gap i a width of spare / gaps, plus one more if i < spare % gaps.
  4. To emit the last line, or any line holding a single word: join with single spaces and pad the right to maxWidth.
  5. The final line is only known to be final after the loop ends, so emit it outside the loop with the left-justified rule.

Walkthrough

words = ["This","is","an","example","of","text","justification."]
maxWidth = 16

packing
   This is an            lengths 4+2+2 = 8, plus 2 spaces = 10, fits
   + example             10 + 1 + 7 = 18 > 16, so line 1 closes
   example of text       7+2+4 = 13, plus 2 = 15, fits
   + justification.      15 + 1 + 14 = 30 > 16, line 2 closes
   justification.        last line

padding line 1: words 8 chars, spare 8, gaps 2
   8 / 2 = 4 each, 8 % 2 = 0 extra
   "This    is    an"      4 + 4 + 4 + 2 + 2 = 16  (gaps of 4 and 4)

padding line 2: words 13 chars, spare 3, gaps 2
   3 / 2 = 1 each, 3 % 2 = 1 extra to the FIRST gap
   "example  of text"      gaps of 2 and 1

padding line 3: last line, left justified
   "justification.  "

Complexity

  • Time — O(total characters): each word is examined once to place it and once to write it.
  • Space — O(total characters): the output holds the whole text; the working line is at most one line long.

Common Pitfalls

  • Stretching the last line. It is left justified, and this is the single most common wrong answer.
  • Stretching a line that holds one word. There are no gaps to distribute into, so it is padded on the right.
  • Giving the extra spaces to the right-hand gaps. The left gaps take them.
  • Forgetting the mandatory single spaces when testing capacity. A line of k words needs k - 1 spaces before any padding, so capacity is not just the sum of the word lengths.
  • Returning a line shorter than maxWidth. Every line, including the last, is padded to the full width.

Full Solution — all languages

class Solution:
    def fullJustify(self, words, maxWidth):
        lines, line, width = [], [], 0

        def justify(parts, used):
            if len(parts) == 1:
                return parts[0] + " " * (maxWidth - used)
            gaps = len(parts) - 1
            spare = maxWidth - used
            base, extra = divmod(spare, gaps)
            out = []
            for i in range(gaps):
                out.append(parts[i])
                out.append(" " * (base + (1 if i < extra else 0)))
            out.append(parts[gaps])
            return "".join(out)

        for w in words:
            # len(line) is the number of single spaces the line already needs.
            if width + len(line) + len(w) > maxWidth:
                lines.append(justify(line, width))
                line, width = [], 0
            line.append(w)
            width += len(w)

        # The last line is left justified, so it is built outside the loop.
        last = " ".join(line)
        lines.append(last + " " * (maxWidth - len(last)))
        return lines
SensAI
Beta
Tap the mic to stop voice mode