Text Justification

Pack words greedily per line; distribute spaces evenly with extras on the left, left-justify the last line.

Hard
Time O(total chars) Space O(total chars)
LeetCode
6 min read
greedy string

Problem#

Given words and maxWidth, fully justify the text so every line is exactly maxWidth characters. Pack as many words as fit per line. Distribute extra spaces evenly (extras on the left); single-word and last lines are left-justified with trailing spaces.

Examples#

  • words = ["This","is","an","example","of","text","justification."], maxWidth = 16["This is an","example of text","justification. "]

Constraints#

  • 1 <= words.length <= 300.

Approach#

Greedy: pack words into a line while their total length plus single-space separators fits maxWidth. Then distribute the remaining space: gaps = wordCount - 1; base = spaces / gaps, extra = spaces % gaps; first extra gaps get one more. Special cases: single-word line (left-justify); last line (single spaces, pad right).

Solution#

Text Justification
class Solution {
public:
vector<string> fullJustify(vector<string>& words, int maxWidth) {
vector<string> ans;
int n = words.size(), i = 0;
while (i < n) {
int j = i, len = 0;
while (j < n && len + (int)words[j].size() + (j - i) <= maxWidth) {
len += words[j].size();
++j;
}
int gaps = j - i - 1;
string line;
if (gaps == 0 || j == n) {
for (int k = i; k < j; ++k) {
line += words[k];
if (k + 1 < j) line += ' ';
}
line += string(maxWidth - line.size(), ' ');
} else {
int totalSpaces = maxWidth - len;
int base = totalSpaces / gaps, extra = totalSpaces % gaps;
for (int k = i; k < j; ++k) {
line += words[k];
if (k + 1 < j) line += string(base + (k - i < extra ? 1 : 0), ' ');
}
}
ans.push_back(line);
i = j;
}
return ans;
}
};

Editorial#

The “fit-as-many-as-possible” packing is itself greedy and not always optimal for cosmetic flow (Knuth’s text-justification DP minimizes a “badness” metric), but it matches the problem spec. Distribution is integer division with the remainder spread to the left gaps.

Complexity#

  • Time: O(total characters).
  • Space: O(total characters).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.