LeetCode #68 Hard

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.

Constraints
  • 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
stringssimulation
Open on LeetCode ↗
02

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 maxWidth minus the letters. Divide them by the number of gaps: every gap gets the quotient, and the first remainder gaps get one more.

The last line and one-word lines skip the division and are padded on the right.

How to spot this pattern

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

03

Approach

Try it first

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.

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def fullJustify(self, words, maxWidth):
▶3 lines = []
▶4 n = len(words)
▶5 i = 0
▶6 while i < n:
▶7 j = i + 1
▶8 width = len(words[i])
▶9 while j < n and width + 1 + len(words[j]) <= maxWidth:
▶10 width += 1 + len(words[j])
▶11 j += 1
▶12 gaps = j - i - 1
▶13 if j == n or gaps == 0:
▶14 text = " ".join(words[i:j])
▶15 lines.append(text + " " * (maxWidth - len(text)))
▶16 else:
▶17 spaces = maxWidth - (width - gaps)
▶18 each, extra = divmod(spaces, gaps)
▶19 text = ""
▶20 for k in range(gaps):
▶21 text += words[i + k] + " " * (each + (1 if k < extra else 0))
▶22 lines.append(text + words[j - 1])
▶23 i = j
▶24 return lines
1This23width 16next wordis4usedline 1 starts with 'This'
line1
width4letters so far
Every line is 16 cells wide, drawn as the dashed slots. Line 1 opens with 'This', 4 letters. A line always takes at least one word, and no word is wider than 16, so it always fits.
1Thisis23width 16next wordan4used+1space+2word=7needed≤16width'is' fits → 7 of 16 used
width7
words2
'is' needs one space in front of it plus 2 letters, 7 cells in all, and 7 is within 16. It joins line 1.
1Thisisan23width 16next wordexample7used+1space+2word=10needed≤16width'an' fits → 10 of 16 used
width10
words3
'an' needs one space in front of it plus 2 letters, 10 cells in all, and 10 is within 16. It joins line 1.
1Thisisan23width 16next wordexample10used+1space+7word=18needed>16width'example' needs 18 > 16 → line 1 is full
width10
j3first word of the next line
'example' would take the line to 18 cells, more than 16. It must start the next line, so line 1 is closed with 3 words.
1Thisisan4423width 16next wordexample16width−8letters=8spaces÷2gaps→4each0extra8 spaces over 2 gaps → 4 each
each4
extra0go to the left gaps
Line 1 has 8 letters, so 8 spaces must fill its 2 gaps. 8 ÷ 2 is 4 exactly, so every gap gets 4 and the line ends flush on both sides.
1Thisisan442example3width 16next wordof7usedline 2 starts with 'example'
line2
width7letters so far
Line 2 opens with 'example', 7 letters. A line always takes at least one word, and no word is wider than 16, so it always fits.
1Thisisan442exampleof3width 16next wordtext7used+1space+2word=10needed≤16width'of' fits → 10 of 16 used
width10
words2
'of' needs one space in front of it plus 2 letters, 10 cells in all, and 10 is within 16. It joins line 2.
1Thisisan442exampleoftext3width 16next wordjustification.10used+1space+4word=15needed≤16width'text' fits → 15 of 16 used
width15
words3
'text' needs one space in front of it plus 4 letters, 15 cells in all, and 15 is within 16. It joins line 2.
1Thisisan442exampleoftext3width 16next wordjustification.15used+1space+14word=30needed>16width'justification.' needs 30 > 16 → line 2 is full
width15
j6first word of the next line
'justification.' would take the line to 30 cells, more than 16. It must start the next line, so line 2 is closed with 3 words.
1Thisisan442exampleoftext213width 16next wordjustification.16width−13letters=3spaces÷2gaps→1each1extra3 spaces over 2 gaps → 1 each, the first gets 1 more
each1
extra1go to the left gaps
Line 2 has 13 letters, so 3 spaces must fill its 2 gaps. 3 ÷ 2 is 1 remainder 1: every gap gets 1 and the first gap gets one more, so the wider gap sits on the left (the numbers under the gaps).
1Thisisan442exampleoftext213justification.width 16next wordnone14usedline 3 starts with 'justification.'
line3
width14letters so far
Line 3 opens with 'justification.', 14 letters. A line always takes at least one word, and no word is wider than 16, so it always fits.
1Thisisan442exampleoftext213justification.pad 2width 16next wordnone16width−14text=2paddinglast line → pad 2 on the right
line"justification." + 2 spaces
No words are left, so this is the last line. It keeps single spaces between its words even though 2 cells are free; the 2 spare cells go at the end.
1Thisisan442exampleoftext213justification.pad 2width 16next wordnone3lines3 lines, each exactly 16 wide
result3 lines
Every word is placed and each row has exactly 16 cells. Only the full lines with two or more words were spread to both edges; the rest were padded on the right.
05

Common pitfalls

Giving the extra spaces to the right-hand gaps

✗ Wrong
text += words[i + k] + " " * (each + (1 if k >= gaps - extra else 0))
✓ Right
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

✗ Wrong
if j == n:
    ...
else:
    each, extra = divmod(spaces, gaps)
✓ Right
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

✗ Wrong
if gaps == 0:  # only one-word lines are padded on the right
✓ 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

✗ Wrong
while j < n and width + len(words[j]) <= maxWidth:
✓ Right
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.

06

Edge cases

A word exactly maxWidth long

No second word can join it, so it forms a one-word line with no padding at all. acknowledgment at width 14 comes back unchanged.

All the words fit on one line

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.

07

Complexity

Time
O(L)
Space
O(L)
L is the size of the output: the number of lines times 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.
08

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.