774. Fully justify words into lines of a fixed width
Terminal output, fixed-width reports and some text renderers lay words out so every line has the same width. The rules are simple to state and easy to get wrong at the edges.
Write justify(words, width). Put as many words as fit on each line, in order, with at least one space between neighbours (greedy packing). Then pad each line to exactly width characters:
A line with two or more words, other than the last line, spreads its extra spaces across the gaps between words as evenly as possible; when they do not divide evenly, the gaps on the left get one more space than the gaps on the right. A line with one word, and the last line, use single spaces between words and are padded with spaces on the right.
Return the list of lines. Every word is non-empty and no longer than width. An empty word list returns an empty list.
def justify(words, width)Example 1
Input: words = ['the', 'quick', 'brown', 'fox', 'jumps'], width = 11
Output: ['the quick', 'brown fox', 'jumps ']
Example 2
Input: words = ['a', 'bb', 'ccc', 'dddd'], width = 6
Output: ['a bb', 'ccc ', 'dddd ']. 'ccc dddd' would need 8 characters
Explanation: So ccc sits alone on its line.
Constraints
- At most 5,000 words.
- 1 <=
len(word)<= width <= 200.
Hint 1
When checking fit, count one space per gap, not the final padding.
Hint 2
The last line follows different rules from the middle lines.
Hint 3
A one-word middle line has zero gaps; avoid dividing by zero.
Common mistakes
- Dividing by zero gaps on a one-word line.
- Giving the extra spaces to the right gaps instead of the left ones.
- Fully justifying the last line.
Understand the idea
Text layout problems are about careful case analysis rather than clever algorithms. Split the work in two clean phases: decide which words go on each line, then decide how to pad that line. divmod is the standard tool for spreading a remainder: base = s // g everywhere, plus one more in the first s % g slots.