Text Justification (LeetCode 68): Solution and Explanation

Hard
Array
String
Simulation

Lay out a list of words into lines that are each exactly maxWidth characters wide. Pack as many words per line as fit, spread the extra spaces between words as evenly as possible with the leftmost gaps getting any surplus, and left-align the final line.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

There is no clever algorithm hiding here. The problem is a careful simulation, and the difficulty is in the rules: which words go on each line, how spaces are split when they do not divide evenly, what happens to a line with a single word, and how the last line differs. Getting a clean structure up front keeps those rules from turning into a tangle of special cases.

Deciding line breaks is greedy. Keep adding words to the current line while they fit, where fitting means the letters plus at least one space between every pair of words stays within maxWidth. If the line currently holds len(line) words with lineLen letters, adding word needs lineLen + len(word) + len(line) characters, because the new word brings one more gap. Greedy packing is what the problem asks for, so there is no need to consider alternatives.

Distributing spaces is where most bugs live. The line needs maxWidth - lineLen spaces in total, spread across len(line) - 1 gaps, with leftover spaces going to the leftmost gaps. The reference solution does this with a neat round-robin: append one space at a time to word i % (len(line) - 1). The first gaps receive the extra spaces automatically. When the line holds a single word there are no gaps, so max(len(line) - 1, 1) makes every space land on that one word, which pads it on the right as the rules require. The last line is joined with single spaces and padded with ljust.

Approach: Greedy packing with round-robin spaces

  1. Keep line, the words on the current line, and lineLen, their total letter count.
  2. For each word, check whether lineLen + len(word) + len(line) > maxWidth, meaning it would not fit with single spaces.
  3. If it does not fit, add maxWidth - lineLen spaces one at a time, each to line[i % max(len(line) - 1, 1)], so the leftmost gaps get the extra spaces.
  4. Join the padded words with no separator, append the result and reset line and lineLen.
  5. Add the word to the (possibly new) line and add its length to lineLen.
  6. After the loop, join the final line with single spaces, pad it on the right with ljust(maxWidth) and append it.

Step-by-step example

words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
  1. "This", "is" and "an" fit, giving lineLen = 8. Adding "example" would need 8 + 7 + 3 = 18, which is over 16.
  2. The first line needs 16 - 8 = 8 spaces over 2 gaps. Round-robin gives 4 to "This" and 4 to "is", producing "This is an".
  3. The next line collects "example", "of" and "text" with lineLen = 13. Adding "justification." needs 13 + 14 + 3 = 30, so the line closes.
  4. It needs 3 spaces over 2 gaps. "example" gets 2 and "of" gets 1, producing "example of text".
  5. "justification." is the last line, so it becomes "justification." followed by two spaces to reach 16 characters.

Code: Python, Java, C++

1class Solution:
2    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
3        result = []
4        line = []
5        lineLen = 0
6
7        for word in words:
8            # Check if adding word would exceed maxWidth
9            if lineLen + len(word) + len(line) > maxWidth:
10                # Justify current line
11                for i in range(maxWidth - lineLen):
12                    line[i % max(len(line) - 1, 1)] += ' '
13                result.append(''.join(line))
14                line, lineLen = [], 0
15
16            line.append(word)
17            lineLen += len(word)
18
19        # Last line: left-justified
20        result.append(' '.join(line).ljust(maxWidth))
21        return result

Time and space complexity

Time

O(L × maxWidth)

Each of the L output lines is built once, and the work per line is proportional to its width, so the total is proportional to the size of the output, which also bounds the input length.

Space

O(L × maxWidth)

The result stores L lines of maxWidth characters. Apart from the output, the current line uses O(maxWidth) space.

Other approaches

Two-pointer lines with arithmetic spacing (time O(L × maxWidth), space O(L × maxWidth))

Find each line's word range with two indices, then compute gaps = count - 1, base = spaces // gaps and extra = spaces % gaps, giving the first extra gaps one additional space. It avoids appending spaces one at a time and is the most common style in Java and C++.

Common mistakes

  • Forgetting the single-word line, where len(line) - 1 is zero and a modulo or division by it crashes.
  • Giving the extra spaces to the rightmost gaps instead of the leftmost.
  • Fully justifying the last line. It must use single spaces and be padded only on the right.
  • Checking only lineLen + len(word) > maxWidth, which ignores the required space between words and overfills lines.

Frequently asked questions

How are extra spaces distributed in Text Justification?

Divide the spaces as evenly as possible across the gaps. When they do not divide evenly, the leftmost gaps each get one more space than the gaps to their right.

Why is the last line handled differently?

The rules say the final line is left-justified, so words are separated by exactly one space and any remaining width is padded on the right.

Is there an algorithm behind Text Justification or is it just simulation?

It is a simulation with a greedy line-breaking rule. The challenge is implementing the spacing rules exactly, which is why it is a common interview test of careful coding rather than algorithm design.