AAlgoLoopSpaced repetition for LeetCode
HARDStringLeetCode ↗

Text Justification

The key idea

Greedily pack as many words as fit per line, then justify that line as a separate sub-problem. For a full line, spread the leftover spaces across the gaps as evenly as possible, giving the extra to the leftmost gaps. The last line (and any single-word line) is left-justified instead.

Problem

Given an array of strings words and a width maxWidth, format the text so that each line has exactly maxWidth characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly maxWidth characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left-justified, and no extra space is inserted between words.

A word is defined as a character sequence consisting of non-space characters only. Each word's length is guaranteed to be greater than 0 and not exceed maxWidth. The input array words contains at least one word.

Constraints

Examples

Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16 Output: [ "This is an", "example of text", "justification. " ]
Input: words = ["What", "must", "be", "acknowledgment", "shall", "be"], maxWidth = 16 Output: [ "What must be", "acknowledgment ", "shall be " ]
Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20 Output: [ "Science is what we", "understand well", "enough to explain to", "a computer. Art is", "everything else we", "do " ]

Complexity

Time: O(n) Space: O(n)

See the full solution

410310
Step-by-step visualization
Start free →

More String problems