68 Text Justification

Given an array of words and a length L, format the text such that each line has exactly L 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 L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do 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.
For example, words:["This", "is", "an", "example", "of", "text", "justification."] L:16.
Return the formatted lines as:
"This is an",
"example of text",
"justification. "
Note:Each word is guaranteed not to exceed L in length.
The Idea: Keep two arrays: one that temporarily fills a list of words that can fit, and another final array solution. Append to the temporary array until it reaches maximum capacity. Then do a round robin kind of traversal through this array until every the amount of spaces full occupy the maximum width as required. Then dump the information into the final array, and reset.
Complexity: O(n + k) where n is the total number of words, and k is the average amount of spaces we justify in a given text. O(n) extra space.
class Solution:
def fullJustify(self, words, maxWidth):
:type words: List[str]
:type maxWidth: int
:rtype: List[str]
res, cur, num_of_letters = [], [], 0
for w in words:
if num_of_letters + len(w) + len(cur) > maxWidth:
# maxWidth - num_of_letters is the amount of spaces that can fit
for i in range(maxWidth - num_of_letters):
# we need to fix the edge case when len(cur) == 1, and then we would mod by zero
cur[i%(len(cur)-1 or 1)] += ' '
cur, num_of_letters = [], 0
# once we reset, add the word that we overcounted
num_of_letters += len(w)
return res + [' '.join(cur).ljust(maxWidth)]
  • What if we allow words to be longer than the width of the line?
    • Then len(w) would need to be removed from the check.