Text Justification
HardTop Interview 150 Arrays & HashingAirbnbKaratSIGSentryVisaCapital OneProblem
You are given a list of words and a line width maxWidth. Arrange the words, in order,
into lines that are each exactly maxWidth characters long.
Fill each line greedily: take as many words as fit with at least one space between neighbours. Then pad with spaces:
- On a normal line, distribute the extra spaces as evenly as possible between words. If they do not divide evenly, the gaps on the left get one more space than the gaps on the right.
- The last line, and any line holding a single word, is left-justified: single spaces between words and all remaining spaces at the end.
Return the list of lines.
Constraints
- 1 ≤ words.length ≤ 300
- 1 ≤ words[i].length ≤ maxWidth ≤ 100
- Words contain no spaces
Examples: pick one to animate
Solutions
Time: Each word is looked at once to place it on a line, and building a line costs its width.
Space: Only the current line is built at a time, apart from the output itself.
Work one line at a time. Starting at word i, keep taking words while their letters plus one space between each pair still fit. Once the line is chosen, count its gaps. For the last line or a single word, join with single spaces and pad the end. Otherwise share the leftover spaces evenly across the gaps, giving the extras to the leftmost gaps.