Text Justification
Given an array of strings words and an integer maxWidth, format the text so that each line has exactly maxWidth characters and is fully justified.
You should pack the words greedily: put as many words as possible in each line. Then add extra spaces ' ' so that every line has exactly maxWidth characters.
For each non-last line:
- Spaces between words should be distributed as evenly as possible.
- If the number of spaces does not divide evenly, the left slots get more spaces than the right slots.
- Lines with only one word should be left-justified.
The last line should be left-justified, meaning words are separated by a single space and any remaining spaces are appended at the end.
Return the formatted lines as an array of strings.
words = ["This","is","an","example","of","text","justification."], maxWidth = 16["This is an","example of text","justification. "]words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16["What must be","acknowledgment ","shall be "]Constraints
- 1 <= words.length <= 300
- 1 <= words[i].length <= 20
- words[i] consists of only English letters and symbols
- 1 <= maxWidth <= 100
- words[i].length <= maxWidth
Asked at 40 companies
Practice questions like this out loud in a mock coding interview with a live AI interviewer. First one free.