Text Justification

Lay out words in lines of a fixed width, with the spare spaces shared out so both edges line up.

You are given an array of strings words and a line width maxWidth. Lay the words out, in order, in lines of exactly maxWidth characters each, following these rules:

Every word is shorter than or as long as maxWidth. Return the lines as a list of strings.

Example 1
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
Output: ["This    is    an", "example  of text", "justification.  "]
Example 2
Input: words = ["What", "must", "be", "acknowledgment", "shall", "be"], maxWidth = 16
Output: ["What   must   be", "acknowledgment  ", "shall be        "]
Explanation: "acknowledgment" is alone on its line, so it keeps its spaces at the end, like the last line.
Solution

The Idea

Open a newspaper and look at a column of text. Every line starts at the same place on the left and ends at the same place on the right, even though the words have different lengths. The printer makes that happen by stretching the spaces between words. Text laid out this way is called justified, and this problem asks us to do the same with lines of maxWidth characters.

Take Example 1, with lines of 16 characters. "This is an" with one space between the words is 10 characters, and adding "example" would need 18, so the first line holds three words. The second line takes "example of text", which is 15 characters with single spaces. Adding "justification." would need 30, so that word starts the third line on its own.

The second line is one character short. Where does the missing character go? Look at the picture below.

The line example of text in 16 boxes. With one space between words it takes 15 characters and leaves 1 spare. Justified, the spare space goes to the left gap, which gets 2 spaces, and the right gap keeps 1.

In the top row, each box holds one character. The three words and two single spaces fill 15 boxes, and the last box is unused. That box becomes a spare space. A line with two gaps cannot split one space evenly, so the rule gives it to the left gap. In the bottom row, the left gap has 2 spaces and the right gap 1: "example  of text".

So each line is two separate choices. First, which words go on it, decided by counting characters with one space between words. Second, how many spaces each gap gets, decided by sharing out the characters left over.

Solution Approach

Turning that idea into code means settling three things: how to tell which words fit on a line, how to share the spaces on a full line, and how to lay out the lines that keep single spaces.

Which words fit on a line

How do we know when a line is full? Count the letters of the words taken so far, plus one space before every word after the first. A new word fits if that count, with the new word and its space added, is still at most maxWidth.

Taking as many words as fit, line by line, without ever going back, is called greedy packing. Going back would never help here: the rules themselves say each line must hold as many words as fit, so the first line is fixed, then the second, and so on.

Sharing the spaces on a full line

How many spaces does each gap get? A line with k words has k - 1 gaps, and the spaces to share are maxWidth minus the letters. Dividing the spaces by the gaps gives what every gap gets, and the remainder is the number of spare spaces left over. The gaps on the left get one spare each, until none are left.

On the first line of Example 1, "This", "is" and "an" have 8 letters, so 8 spaces go into 2 gaps: 4 each, nothing left over. On the second line, 3 spaces go into 2 gaps: 1 each, with 1 left over for the left gap, as in the picture.

Lines that keep single spaces

Which lines skip the sharing? The last line, by the rules, and any line with only one word. A one-word line has no gaps at all, so dividing by the number of gaps would divide by zero. Both kinds of line are written with one space between words, and the rest of the line is filled with spaces at the end.

Java Solution

The method fullJustify works in these steps:

  1. First, create the list lines for the result, and set start to 0, the position of the first word of the current line. A loop builds one line per pass while start is inside the array.
  2. Find the words of the line with a second loop inside the first. It moves end forward from start and adds each word's length to letters, while letters + words[end].length() + (end - start) is at most maxWidth. The term end - start counts one space before each word after the first. When it stops, the line holds the words from start up to, but not including, end.
  3. Count the gaps between those words, one fewer than the words, into gaps, and start an empty StringBuilder named line.
  4. If this is the last line (end reached the end of the array) or gaps is 0, append the words with one space between them, then pad the end with " ".repeat(maxWidth - line.length()).
  5. Otherwise, work out spaces, the characters left after the letters. each is spaces / gaps, and extra is spaces % gaps, the spare spaces. Append each word, and after it, unless it is the last word, each spaces plus one more for the first extra gaps.
  6. Add the finished line to lines and set start to end, so the next pass begins with the first word that did not fit. When all words are placed, return lines.

The main method runs both examples, a line with three gaps and an uneven number of spaces, and a single word exactly as long as the line. It prints each line in quotes, so the spaces at the end show.

Java
import java.util.ArrayList;
import java.util.List;

public class TextJustification {

    public static List<String> fullJustify(String[] words, int maxWidth) {
        List<String> lines = new ArrayList<>();
        int start = 0;
        while (start < words.length) {
            int end = start;
            int letters = 0;
            while (end < words.length
                    && letters + words[end].length() + (end - start) <= maxWidth) {
                letters += words[end].length();   // the word fits with one space before it
                end++;
            }
            int gaps = end - start - 1;
            StringBuilder line = new StringBuilder();
            if (end == words.length || gaps == 0) {   // last line or one word: left-justify
                for (int k = start; k < end; k++) {
                    if (k > start) {
                        line.append(' ');
                    }
                    line.append(words[k]);
                }
                line.append(" ".repeat(maxWidth - line.length()));
            } else {
                int spaces = maxWidth - letters;
                int each = spaces / gaps;
                int extra = spaces % gaps;          // the first "extra" gaps get one more
                for (int k = start; k < end; k++) {
                    line.append(words[k]);
                    int gap = k - start;
                    if (gap < gaps) {
                        line.append(" ".repeat(each + (gap < extra ? 1 : 0)));
                    }
                }
            }
            lines.add(line.toString());
            start = end;
        }
        return lines;
    }

    static void show(String[] words, int maxWidth) {
        for (String line : fullJustify(words, maxWidth)) {
            System.out.println("\"" + line + "\"");
        }
    }

    public static void main(String[] args) {
        show(new String[] {"This", "is", "an", "example", "of", "text", "justification."}, 16);
        System.out.println();
        show(new String[] {"What", "must", "be", "acknowledgment", "shall", "be"}, 16);
        System.out.println();
        show(new String[] {"one", "two", "three", "four", "five"}, 20);
        System.out.println();
        show(new String[] {"justify"}, 7);
    }
}

Running it prints:

Output
"This    is    an"
"example  of text"
"justification.  "

"What   must   be"
"acknowledgment  "
"shall be        "

"one  two  three four"
"five                "

"justify"

Look at the second line, "example  of text": the spare space went to the left gap, as in the picture. Further down, in Example 2, "acknowledgment  " is alone on its line, so gaps is 0 and the two free characters go at the end. The last line of Example 2, "shall be", keeps a single space and gets 8 spaces at the end.

The "one  two  three four" line has 15 letters, so 5 spaces go into its 3 gaps. Each gap gets 1, and the 2 spare spaces go one each to the two left gaps: 2, 2 and 1. The word "five" is the last line, padded with 16 spaces. At the bottom, "justify" fills its 7-character line exactly, so repeat(0) adds nothing.

The original implementation, TextJustification.java, is on GitHub.

Complexity

The work is one look at each word to place it, plus writing every character of the output once.

  • Time: O(L), where L is the total length of the output, the number of lines times maxWidth. The inner loop checks each word once to place it (plus one failed check per line), and every letter and space is appended exactly once.
  • Space: O(maxWidth) besides the output. Only one StringBuilder line is built at a time, and it never grows past maxWidth characters.

Filling each line as far as it goes before starting the next is greedy packing, the same idea as in Boats to Save People, with lines in place of boats.