Even-Width Paragraph Formatter
StringsAuto-graded · 22 test casesLast updated
Greedily pack words into lines of a fixed width, then pad each line with spaces so it is exactly that wide, handling single-word and final lines separately.
Even-Width Paragraph Formatter
You are given a list of words and a target line width width. Format the words into lines so that every line is exactly width characters long.
Step 1: Packing words into lines
Process the words in their given order, without reordering or splitting them. Fill each line greedily: keep adding the next word to the current line as long as the line still fits when the words on it are separated by exactly one space. In other words, a line holding k words with total letter count L is allowed only if L + (k - 1) <= width. As soon as the next word would not fit, close the current line and begin a new line with that word.
Step 2: Padding each line to exactly width
Once the words of a line are chosen, build the line text as follows.
- Regular line (it holds two or more words and is not the final line): spread the spaces so the line is exactly
widthcharacters long. The number of spaces to place in total iswidthminus the combined length of the words. They go into the gaps between neighbouring words. Every gap gets the same number of spaces, except that if the spaces do not divide evenly, the leftmost gaps each receive one extra space. Any two gaps therefore differ in size by at most one, and gaps to the left are never smaller than gaps to the right. - Single-word line (any line that contains only one word) and the final line of the output: place the words separated by one space each, and append spaces on the right until the length is
width.
Return the list of formatted lines in order. Every string in the result must have length exactly width, and trailing spaces are significant.
Input
words: a list of non-empty strings, none containing a space.width: a positive integer.
Output
A list of strings, each of length exactly width.
Constraints
1 <= len(words)1 <= len(word) <= widthfor every word, so every word fits on a line by itself- Words contain no space characters
widthis a positive integer
Examples
Example 1
Input: justify_text(['This', 'is', 'an', 'example', 'of', 'text', 'justification'], 16)
Output: ['This is an', 'example of text', 'justification ']
Example 2
Input: justify_text(['This', 'is', 'an', 'example', 'of', 'text', 'display'], 16)
Output: ['This is an', 'example of text', 'display ']
Hints
Hint 1
Separate the work into two phases for each line: first decide which words belong together, then decide how to lay out the spaces.
Hint 2
While extending a line starting at index `start`, adding `words[end]` needs `end - start` single spaces. Track the sum of word lengths separately so the fit test is `letters + len(words[end]) + (end - start) <= width`.
Hint 3
For a regular line, use `divmod(total_spaces, gaps)` to get the base gap size and the number of leftmost gaps that get one extra space. Handle single-word lines and the last line first, which also avoids dividing by zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the task as two separate phases that repeat for each line.
1. Packing. Starting at the first unused word start, extend end while the next word still fits. A line holding words start .. end-1 plus the candidate words[end] needs end - start single spaces (one before every word except the first). So the candidate fits when:
letters + len(words[end]) + (end - start) <= width
Here letters is the sum of the lengths of the words already on the line. Because every word has length at most width, each line takes at least one word, so the outer loop always advances.
2. Formatting. With count = end - start words on the line:
- If
count == 1or this is the last line (end == n), join the words with single spaces and pad on the right towidth. - Otherwise there are
gaps = count - 1gaps andspaces = width - lettersspaces to place. Computebase, extra = divmod(spaces, gaps). Each gap getsbasespaces, and the firstextragaps get one more, so the larger gaps are on the left.
Why it is correct
- Packing follows the stated greedy rule exactly, so the choice of words on every line matches the specification.
base * gaps + extra == spaces, soletters + spaces == widthand each regular line has exactlywidthcharacters.- Only gaps with index
< extrareceive an extra space, which are the leftmost ones, and gap sizes differ by at most one. - The single-word case is handled before any division, so there is no division by zero. For left-justified lines, the single-space join has length at most
widthby the packing rule, so the padding is never negative.
Complexity
- Time: O(N + L * width), where N is the total number of characters in the words and L is the number of output lines. This is linear in the size of the input plus the output.
- Space: O(L * width) for the output; auxiliary space is O(width) for building one line.
Reference solution
from typing import List
def justify_text(words: List[str], width: int) -> List[str]:
result = []
start = 0
n = len(words)
while start < n:
end = start
letters = 0
while end < n and letters + len(words[end]) + (end - start) <= width:
letters += len(words[end])
end += 1
count = end - start
is_last = end == n
if count == 1 or is_last:
line = " ".join(words[start:end])
result.append(line + " " * (width - len(line)))
else:
gaps = count - 1
spaces = width - letters
base, extra = divmod(spaces, gaps)
parts = []
for i in range(gaps):
parts.append(words[start + i])
parts.append(" " * (base + (1 if i < extra else 0)))
parts.append(words[end - 1])
result.append("".join(parts))
start = end
return result