Text Justification

Hard · Strings · Array · String · Simulation

Problem

Lay out the list words as fully justified text, every line exactly maxWidth characters wide.

Each word is a run of non-space characters, and no word is longer than maxWidth. Return the lines.

Examples

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

Line 1 has 8 letters and 8 spaces in two gaps: 4 and 4. Line 2 has 13 letters and 3 spaces in two gaps: 2 on the left, 1 on the right.

Input: words = ["What", "must", "be", "acknowledgment", "shall", "be"], maxWidth = 16
Output: ["What   must   be", "acknowledgment  ", "shall be        "]

acknowledgment is alone on its line, so it is left-justified; the last line keeps single spaces.

Input: words = ["a", "b", "c", "dddddddd"], maxWidth = 8
Output: ["a   b  c", "dddddddd"]

Five spaces over two gaps: 3 on the left, 2 on the right.

Constraints

Approaches

Follow-up

Greedy packing can leave a very short line in the middle. With a cost per line such as the square of its trailing space, dynamic programming finds the line breaks with the least total cost (the idea behind TeX's line breaking). And how would you center each line instead?

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…