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 wordsmaxWidthmaxWidth
- Put as many words on each line as fit, with at least one space between two words.
- Share the extra spaces between the words as evenly as possible. If they do not divide evenly, the gaps on the left get one more space than the gaps on the right.
- The last line, and any line with only one word, keeps one space between words and fills the rest of the line with spaces at the end.
Every word is shorter than or as long as maxWidth
Example 1
Output: ["This is an", "example of text", "justification. "]
Example 2
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.
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
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.
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
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
- First, create the list
for the result, and setlines to 0, the position of the first word of the current line. A loop builds one line per pass whilestart is inside the array.start - Find the words of the line with a second loop inside the first. It moves
forward fromend and adds each word's length tostart , whileletters is at mostletters + words[end].length() + (end - start) . The termmaxWidth counts one space before each word after the first. When it stops, the line holds the words fromend - start up to, but not including,start .end - Count the gaps between those words, one fewer than the words, into
, and start an emptygaps namedStringBuilder .line - If this is the last line (
reached the end of the array) orend is 0, append the words with one space between them, then pad the end withgaps ." ".repeat(maxWidth - line.length()) - Otherwise, work out
, the characters left after the letters.spaces iseach , andspaces / gaps isextra , the spare spaces. Append each word, and after it, unless it is the last word,spaces % gaps spaces plus one more for the firsteach gaps.extra - Add the finished line to
and setlines tostart , so the next pass begins with the first word that did not fit. When all words are placed, returnend .lines
The main
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:
"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""acknowledgment "gaps"shall be"
The "one two three four""justify"repeat(0)
The original implementation,
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
. 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.maxWidth - Space: O(maxWidth) besides the output. Only one
line is built at a time, and it never grows pastStringBuilder characters.maxWidth
Filling each line as far as it goes before starting the next is greedy packing, the same idea as in