Ctrl K

Justify the Lines

Hard
You get a list of words words and a line width width. Break the text into lines and justify it so that every line is exactly width characters long. - Lines are filled greedily: each line takes as many consecutive words as fit with at least one space between neighbouring words. - Spaces between words are spread 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 holding a single word, and the last line of the text, are left-aligned: words are separated by one space and the rest of the line is padded with spaces on the right. Return the list of resulting lines.
Example 1
words=['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'it'], width=14 → ['the      quick', 'brown      fox', 'jumps over it ']

The first line takes "the quick" (9 characters); "brown" no longer fits. The 5 spare spaces all go into the single gap. The second line has three words and 3 spare spaces: the left gap gets 2 extra, the right one gets 1. The last line is left-aligned.

Example 2
words=['a', 'bb', 'ccc'], width=4 → ['a bb', 'ccc ']

"a bb" is exactly 4 characters. "ccc" is the last line and gets one trailing space.

Example 3
words=['notebook', 'pen'], width=8 → ['notebook', 'pen     ']

Each word sits on its own line; a one-word line is padded on the right.

Constraints
  • 1 ≤ len(words) ≤ 300
  • 1 ≤ len(words[i]) ≤ 20
  • words[i] contains no spaces
  • 1 ≤ width ≤ 100
  • len(words[i]) ≤ width
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSimultaneous Chess Moves HardPump Rods at Their Peak HardWords Read Down the Columns MediumA One-Variable Language EasySplit Text at the Marks Medium
loading Python…
Input
words=['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'it'], width=14
Expected
['the      quick', 'brown      fox', 'jumps over it ']

Run checks the first 3 tests in your browser. Submit checks all 104 tests on the server, hidden ones included.