Text Justification
Text Justification is LeetCode 68 (Hard). You get an array of words and a width maxWidth, and you lay the words out as fully justified text: a list of lines, each exactly maxWidth characters long.
- Put as many words on each line as will fit, with at least one space between neighbours.
- Spread the spaces so each line touches both edges. When they do not split evenly, the gaps on the left get the extra spaces.
- The last line, and any line holding a single word, is left-justified instead: single spaces between words, then spaces on the right up to
maxWidth.
No word is longer than maxWidth, so every word fits on a line by itself.
- 1 <= words.length <= 300
- 1 <= words[i].length <= 20
- words[i] consists of only English letters and symbols.
- 1 <= maxWidth <= 100
- words[i].length <= maxWidth
Intuition
The problem is two separate jobs, and keeping them apart is what makes the code short.
- Choosing a line's words: a line of k words needs their letters plus k − 1 single spaces. Keep adding words while that total stays within
maxWidth. The statement asks for exactly this, so there is no smarter split to search for. - Placing the spaces: once the words are fixed, the spaces to place are
maxWidthminus the letters. Divide them by the number of gaps: every gap gets the quotient, and the firstremaindergaps get one more.
The last line and one-word lines skip the division and are padded on the right.
"Format text into lines of a fixed width" with no cost to minimise is a simulation: the rules decide every line break, so the work is packing greedily and counting spaces exactly. If the task instead asks for the neatest breaks (least wasted space), it is Word Wrap, a dynamic programming problem.
Approach
Before reading on, work out how many characters a line of k words takes at minimum, and how 7 spaces should be shared between 3 gaps. Then decide which lines break the even-spread rule. Aim for time linear in the size of the output.
Start a line at the next word
Begin a new line with words[i] and set width to its length. Every line holds at least one word, and no word is longer than maxWidth, so this first word always fits.
Add words while they fit
Word j fits if width + 1 + len(words[j]) <= maxWidth. The + 1 is the single space it needs in front of it. Stop at the first word that does not fit, because it has to open the next line.
Left-justify the last line and one-word lines
If the line uses up the last word, or holds only one word, join its words with single spaces and add spaces on the right until it is maxWidth long. A one-word line has no gap to widen, so all of its padding goes at the end.
Share the spaces over the gaps
Otherwise the line has gaps = words − 1 and maxWidth − letters spaces to place. divmod gives each and extra: every gap gets each spaces and the first extra gaps get one more. The gaps then differ by at most one, with the wider ones on the left.
Continue from the word that did not fit
Append the finished line, set i = j, and repeat until every word is placed. Each word is read once, so the loop ends after one pass over the input.
Code in Python, C++ and Java
Common pitfalls
Giving the extra spaces to the right-hand gaps
text += words[i + k] + " " * (each + (1 if k >= gaps - extra else 0))
text += words[i + k] + " " * (each + (1 if k < extra else 0))
The line example of text at width 16 has 3 spaces for 2 gaps. The expected line is example of text, with the wider gap first; handing the extra space to the last gap gives example of text, which is rejected.
Dividing by the gap count on a one-word line
if j == n:
...
else:
each, extra = divmod(spaces, gaps)if j == n or gaps == 0:
...
else:
each, extra = divmod(spaces, gaps)In ["What", "must", "be", "acknowledgment", "shall", "be"] at width 16, acknowledgment sits alone on line 2, so gaps is 0 and the division crashes. A one-word line has to take the left-justified branch.
Spreading the last line across the width
if gaps == 0: # only one-word lines are padded on the right
if j == n or gaps == 0:
The last line of the same example holds shall be. It must come out as shall be followed by 8 spaces, not shall be. The last line is left-justified even when it has several words.
Leaving out the space in the fit test
while j < n and width + len(words[j]) <= maxWidth:
while j < n and width + 1 + len(words[j]) <= maxWidth:
With ["ab", "cd"] and width 4, the wrong test sees 2 + 2 = 4 and puts both words on one line. But ab cd needs 5 characters, so the line overflows the width.
Edge cases
maxWidth longNo second word can join it, so it forms a one-word line with no padding at all. acknowledgment at width 14 comes back unchanged.
That single line is also the last line, so it is left-justified: ["a", "b"] at width 5 gives a b plus 2 spaces, not a b.
Complexity
maxWidth, at most 300 × 100 characters here. Each word is read once by the fit test and copied once into its line, and every space in the output is written once. The output itself takes the O(L) space.Text Justification FAQ
Is Text Justification a dynamic programming problem?
No. Here the rules fix every line break: a line always takes as many words as fit, so a greedy pass is the whole answer. The dynamic programming version is Word Wrap, where you may move a word down to the next line to make the trailing space more even across lines, and the goal is the lowest total cost.
Is there a shorter way to share out the spaces?
You can hand them out one at a time, round-robin: the s-th spare space goes to gap s % gaps. Because the round starts again at the left gap, the leftover spaces land on the left gaps, giving the same lines as divmod. It does one step per space instead of one per gap, which is still fast at width 100.