Problem · Array
Text Justification
Learn this problemProblem statement
Given an array of words and an integer maxWidth, format the words into lines of exactly maxWidth characters.
- Pack each line greedily with as many words as fit, counting at least one space between adjacent words.
- For every non-final line with at least two words, distribute spaces as evenly as possible. When they do not divide evenly, earlier gaps receive one extra space.
- Left-justify the final line and every single-word line: place one space between words and pad the right side with spaces.
Return the formatted lines in order. Input words contain no spaces, and every word fits within maxWidth.
Function
fullJustify(words: String[], maxWidth: int) → String[]Examples
Example 1
words = ["This","is","an","example","of","text","justification."]maxWidth = 16return = ["This is an","example of text","justification. "]The first two lines are fully justified to width 16. The final single-word line is padded on the right.
Example 2
words = ["What","must","be","acknowledgment","shall","be"]maxWidth = 16return = ["What must be","acknowledgment ","shall be "]The long middle word forms a single-word line, and the final line uses one internal space plus right padding.
Example 3
words = ["a"]maxWidth = 3return = ["a "]The only line is the final line, so the word is followed by two padding spaces.
Constraints
1 <= words.length <= 100001 <= words[i].length <= maxWidth <= 10000- Words contain printable non-space ASCII characters.
- The total number of word characters is at most
200000.