Text Justification
Hard
Topics
Given an array of words and a width maxWidth, format the text so that every line has exactly maxWidth characters and is both left and right justified.
Pack as many words onto a line as will fit, where words on a line are separated by at least one space. Then pad with spaces so the line is exactly maxWidth wide:
- Spaces between words are distributed as evenly as possible. If they do not divide evenly, the left gaps take the extra space.
- The last line is left justified instead: single spaces between words, then padding on the right.
- A line holding one word is also left justified, padded on the right.
Return the list of lines.
The judge joins the returned lines with | so the trailing spaces on a line stay visible, since a line of text contains spaces of its own and could not otherwise be told apart from two lines.
Example 1
Input: words = ["This","is","an","example","of","text","justification."], maxWidth = 16 Output: ["This is an","example of text","justification. "] Explanation: Line 1 holds 8 characters of words and 8 spare spaces over 2 gaps, which divides evenly into gaps of 4 and 4. Line 2 has 3 spare over 2 gaps, so the left gap takes the extra and the gaps are 2 and 1. The last line is left justified instead of stretched.
Example 2
Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16 Output: ["What must be","acknowledgment ","shall be "] Explanation: Line 2 holds one word, so it is left justified and padded right rather than stretched.
Example 3
Input: words = ["a"], maxWidth = 3 Output: ["a "] Explanation: A single word is the last line, so it is left justified and padded to the full width.
Constraints
- 1 <= words.length <= 300
- 1 <= words[i].length <= 20
- 1 <= maxWidth <= 100
- words[i].length <= maxWidth
Editorial — intuition, approach, complexity and pitfalls
Intuition
There is no insight to find here; the difficulty is entirely in the number of rules and the fact that three of them contradict the main one. This is a problem about reading the specification carefully and then not making an arithmetic slip.
Split it in two. First decide which words go on which line, which is purely a matter of capacity: a line can hold the next word if the words already on it, plus one space each, plus the new word, still fit. Then, separately, decide how to pad a line you have already chosen.
Keeping those two phases apart is what makes the code manageable, because the padding rule depends on facts the packing phase does not care about — whether the line is the last one, and whether it holds a single word.
The even-distribution arithmetic is the part most people get wrong. With gaps gaps and spare spaces to place, every gap gets spare / gaps and the first spare % gaps gaps get one extra. Writing it that way avoids a loop that dribbles spaces out one at a time and miscounts.
Approach
- Walk the words, accumulating a current line. Before adding a word, check whether
width_so_far + len(line) + len(word) <= maxWidth, wherelen(line)is the number of single spaces already required. - When a word does not fit, emit the current line and start a new one with that word.
- To emit a line that is not the last and holds more than one word: let
gaps = len(line) - 1andspare = maxWidth - total_word_length. Give gapia width ofspare / gaps, plus one more ifi < spare % gaps. - To emit the last line, or any line holding a single word: join with single spaces and pad the right to
maxWidth. - The final line is only known to be final after the loop ends, so emit it outside the loop with the left-justified rule.
Walkthrough
words = ["This","is","an","example","of","text","justification."]
maxWidth = 16
packing
This is an lengths 4+2+2 = 8, plus 2 spaces = 10, fits
+ example 10 + 1 + 7 = 18 > 16, so line 1 closes
example of text 7+2+4 = 13, plus 2 = 15, fits
+ justification. 15 + 1 + 14 = 30 > 16, line 2 closes
justification. last line
padding line 1: words 8 chars, spare 8, gaps 2
8 / 2 = 4 each, 8 % 2 = 0 extra
"This is an" 4 + 4 + 4 + 2 + 2 = 16 (gaps of 4 and 4)
padding line 2: words 13 chars, spare 3, gaps 2
3 / 2 = 1 each, 3 % 2 = 1 extra to the FIRST gap
"example of text" gaps of 2 and 1
padding line 3: last line, left justified
"justification. "Complexity
- Time — O(total characters): each word is examined once to place it and once to write it.
- Space — O(total characters): the output holds the whole text; the working line is at most one line long.
Common Pitfalls
- Stretching the last line. It is left justified, and this is the single most common wrong answer.
- Stretching a line that holds one word. There are no gaps to distribute into, so it is padded on the right.
- Giving the extra spaces to the right-hand gaps. The left gaps take them.
- Forgetting the mandatory single spaces when testing capacity. A line of
kwords needsk - 1spaces before any padding, so capacity is not just the sum of the word lengths. - Returning a line shorter than
maxWidth. Every line, including the last, is padded to the full width.
Full Solution — all languages
class Solution:
def fullJustify(self, words, maxWidth):
lines, line, width = [], [], 0
def justify(parts, used):
if len(parts) == 1:
return parts[0] + " " * (maxWidth - used)
gaps = len(parts) - 1
spare = maxWidth - used
base, extra = divmod(spare, gaps)
out = []
for i in range(gaps):
out.append(parts[i])
out.append(" " * (base + (1 if i < extra else 0)))
out.append(parts[gaps])
return "".join(out)
for w in words:
# len(line) is the number of single spaces the line already needs.
if width + len(line) + len(w) > maxWidth:
lines.append(justify(line, width))
line, width = [], 0
line.append(w)
width += len(w)
# The last line is left justified, so it is built outside the loop.
last = " ".join(line)
lines.append(last + " " * (maxWidth - len(last)))
return linesimport java.util.*;
class Solution {
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> lines = new ArrayList<>();
List<String> line = new ArrayList<>();
int width = 0;
for (String w : words) {
if (width + line.size() + w.length() > maxWidth) {
lines.add(justifyLine(line, width, maxWidth));
line = new ArrayList<>();
width = 0;
}
line.add(w);
width += w.length();
}
StringBuilder last = new StringBuilder(String.join(" ", line));
while (last.length() < maxWidth) last.append(' ');
lines.add(last.toString());
return lines;
}
private String justifyLine(List<String> parts, int used, int maxWidth) {
if (parts.size() == 1) {
StringBuilder one = new StringBuilder(parts.get(0));
while (one.length() < maxWidth) one.append(' ');
return one.toString();
}
int gaps = parts.size() - 1;
int spare = maxWidth - used;
int base = spare / gaps, extra = spare % gaps;
StringBuilder out = new StringBuilder();
for (int i = 0; i < gaps; i++) {
out.append(parts.get(i));
int pad = base + (i < extra ? 1 : 0);
for (int j = 0; j < pad; j++) out.append(' ');
}
out.append(parts.get(gaps));
return out.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> lines, line;
int width = 0;
auto justify = [&](const vector<string>& parts, int used) {
if (parts.size() == 1) return parts[0] + string(maxWidth - used, ' ');
int gaps = (int)parts.size() - 1;
int spare = maxWidth - used;
int base = spare / gaps, extra = spare % gaps;
string out;
for (int i = 0; i < gaps; i++) {
out += parts[i];
out += string(base + (i < extra ? 1 : 0), ' ');
}
out += parts[gaps];
return out;
};
for (const string& w : words) {
if (width + (int)line.size() + (int)w.size() > maxWidth) {
lines.push_back(justify(line, width));
line.clear();
width = 0;
}
line.push_back(w);
width += (int)w.size();
}
string last;
for (size_t i = 0; i < line.size(); i++) {
if (i) last += " ";
last += line[i];
}
last += string(maxWidth - (int)last.size(), ' ');
lines.push_back(last);
return lines;
}
};/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/ var fullJustify = function(words, maxWidth) {
const lines = [];
let line = [], width = 0;
const justify = (parts, used) => {
if (parts.length === 1) return parts[0] + " ".repeat(maxWidth - used);
const gaps = parts.length - 1;
const spare = maxWidth - used;
const base = Math.floor(spare / gaps), extra = spare % gaps;
let out = "";
for (let i = 0; i < gaps; i++) {
out += parts[i] + " ".repeat(base + (i < extra ? 1 : 0));
}
return out + parts[gaps];
};
for (const w of words) {
if (width + line.length + w.length > maxWidth) {
lines.push(justify(line, width));
line = [];
width = 0;
}
line.push(w);
width += w.length;
}
const last = line.join(" ");
lines.push(last + " ".repeat(maxWidth - last.length));
return lines;
};