Text Justification (LeetCode 68): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Keep
line, the words on the current line, andlineLen, their total letter count. - For each word, check whether
lineLen + len(word) + len(line) > maxWidth, meaning it would not fit with single spaces. - If it does not fit, add
maxWidth - lineLenspaces one at a time, each toline[i % max(len(line) - 1, 1)], so the leftmost gaps get the extra spaces. - Join the padded words with no separator, append the result and reset
lineandlineLen. - Add the word to the (possibly new) line and add its length to
lineLen. - 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
- "This", "is" and "an" fit, giving
lineLen = 8. Adding "example" would need 8 + 7 + 3 = 18, which is over 16. - 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".
- The next line collects "example", "of" and "text" with
lineLen = 13. Adding "justification." needs 13 + 14 + 3 = 30, so the line closes. - It needs 3 spaces over 2 gaps. "example" gets 2 and "of" gets 1, producing "example of text".
- "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 result1class Solution {
2 public List<String> fullJustify(String[] words, int maxWidth) {
3 List<String> result = new ArrayList<>();
4 List<String> line = new ArrayList<>();
5 int lineLen = 0;
6
7 for (String word : words) {
8 if (lineLen + word.length() + line.size() > maxWidth) {
9 // Justify current line
10 for (int i = 0; i < maxWidth - lineLen; i++) {
11 int idx = i % Math.max(line.size() - 1, 1);
12 line.set(idx, line.get(idx) + " ");
13 }
14 result.add(String.join("", line));
15 line = new ArrayList<>();
16 lineLen = 0;
17 }
18 line.add(word);
19 lineLen += word.length();
20 }
21
22 // Last line: left-justified
23 StringBuilder lastLine = new StringBuilder(String.join(" ", line));
24 while (lastLine.length() < maxWidth) lastLine.append(" ");
25 result.add(lastLine.toString());
26 return result;
27 }
28}1class Solution {
2public:
3 vector<string> fullJustify(vector<string>& words, int maxWidth) {
4 vector<string> result;
5 vector<string> line;
6 int lineLen = 0;
7
8 for (const string& word : words) {
9 if (lineLen + word.size() + line.size() > maxWidth) {
10 // Justify current line
11 for (int i = 0; i < maxWidth - lineLen; i++) {
12 line[i % max((int)line.size() - 1, 1)] += ' ';
13 }
14 string justified;
15 for (const string& w : line) justified += w;
16 result.push_back(justified);
17 line.clear();
18 lineLen = 0;
19 }
20 line.push_back(word);
21 lineLen += word.size();
22 }
23
24 // Last line: left-justified
25 string lastLine;
26 for (int i = 0; i < line.size(); i++) {
27 if (i > 0) lastLine += ' ';
28 lastLine += line[i];
29 }
30 lastLine += string(maxWidth - lastLine.size(), ' ');
31 result.push_back(lastLine);
32 return result;
33 }
34};Time and space complexity
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.
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) - 1is 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.