Given an array of words and a width maxWidth, format the text such 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 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.

Note:


       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.


Example 1:


Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
   "This    is    an",
   "example  of text",
   "justification.  "
]


Example 2:


Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
  "What   must   be",
  "acknowledgment  ",
  "shall be        "
]
Explanation: Note that the last line is "shall be    " instead of "shall     be",
             because the last line must be left-justified instead of fully-justified.
             Note that the second line is also left-justified becase it contains only one word.


Example 3:


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                  "
]

Difficulty: interview

Starter code:

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        

Solutions:
class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         def make_str(buffer, length, last):
             if last:
                 return ' '.join(buffer) + ' ' * (maxWidth - length)
             space = maxWidth - (length - len(buffer) + 1)
             cnt = len(buffer) - 1
             tmp = ''
             if cnt == 0:
                 tmp = buffer[0] + ' ' * space
             else:
                 spaces = [space // cnt] * cnt
                 for i in range(space % cnt):
                     spaces[i] += 1
                 spaces.append(0)
                 for s, b in zip(spaces, buffer):
                     tmp += b + ' ' * s
             return tmp
 
         res = []
         buffer = []
         length = 0
         for w in words:
             lw = len(w)
             if lw > maxWidth:
                 continue
             if len(buffer) == 0:
                 buffer.append(w)
                 length = lw
             elif length + lw + 1 <= maxWidth:
                 buffer.append(w)
                 length = length + lw + 1
             else:
                 tmp = make_str(buffer, length, False)
                 res.append(tmp)
                 buffer = [w]
                 length = lw
         if len(buffer) > 0:
             tmp = make_str(buffer, length, True)
             res.append(tmp)
 
         return res


class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         A=[]
         for i in range(len(words)):
             A.append(len(words[i]))
         temp=0
         k=0
         B=[]
         for i in range(len(A)):
             #if i==len(A)-1:
                 #B.append
             if temp==0:
                 temp=A[i]
             elif (temp+1+A[i])>maxWidth:
                 if i-k==1:
                     B.append([k,i,0,0])
                 else:
                     B.append([k,i,(maxWidth-temp+i-k-1)//(i-k-1),(maxWidth-temp+i-k-1)%(i-k-1)])
                 temp=A[i]
                 k=i
             else:
                 temp=temp+1+A[i]
             if i==len(A)-1:
                 B.append([k,i+1,1,0])
         str1=''
         ans=[]
         for i in range(len(B)):
             for j in range(B[i][0],B[i][1]):
                 if j==B[i][0]:
                     str1+=words[B[i][0]]
                 elif B[i][3]:
                     str1=str1+(B[i][2]+1)*' '+words[j]
                     B[i][3]-=1
                 else:
                     str1=str1+B[i][2]*' '+words[j]
             if i == len(B) - 1 or B[i][1]-B[i][0]==1:
                 str1=str1+(maxWidth-len(str1))*' '
             ans.append(str1)
             str1=''
         return ans
             
                 
             
                        


class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         currLine = []
         charCount = 0
         result = []
         for word in words:
             if charCount + len(currLine) + len(word) <= maxWidth:
                 charCount += len(word)
                 currLine.append(word)
             else:
                 thisLine = currLine[0]
                 for i in range(1, len(currLine)):
                     thisLine += ' ' * ((maxWidth - charCount) // (len(currLine) - 1))
                     if i <= (maxWidth - charCount) % (len(currLine) - 1):
                         thisLine += ' '
                     thisLine += currLine[i]
                 
                 if len(thisLine) < maxWidth:
                     thisLine += ' ' * (maxWidth - len(thisLine))
                 
                 result.append(thisLine)
                 currLine = [word]
                 charCount = len(word)
                 
         if len(currLine) > 0:
             lastLine = ' '.join(currLine)
             if len(lastLine) < maxWidth:
                 lastLine += ' ' * (maxWidth - len(lastLine))
             result.append(lastLine)
         
         if len(result) == 0:
             return ['']
         
         return result

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:
                 for i in range(maxWidth - num_of_letters):
                     cur[i%(len(cur)-1 or 1)] += ' '
                 res.append(''.join(cur))
                 cur, num_of_letters = [], 0
             cur += [w]
             num_of_letters += len(w)
         return res + [' '.join(cur).ljust(maxWidth)]

class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         if words == [""]:
             s = ' '*maxWidth
             return [s]
         new = []
         for word in words:
             new.append([word,len(word)])
         res = []
         curr_length = 0
         start = 0
         print(new)
         for i in range(len(new)):
             if new[i][1] > maxWidth:
                 return False
             else:
                 if curr_length + (i-start) + new[i][1] > maxWidth:
                     if i-1-start == 0:
                         jiange = maxWidth-curr_length
                         s = ''
                         s += new[i-1][0]
                         s += ' '*(maxWidth-curr_length)
                         res.append(s)
                     else:
                         if (maxWidth-curr_length)%(i-1-start) != 0:
                             jiange = (maxWidth-curr_length)//(i-1-start)
                             k = jiange
                             num = i-2-start
                             while num>0:
                                 if (maxWidth-curr_length-k)%(num) != 0:
                                     k += jiange
                                     num -= 1
                                 else:
                                     break
                         else:
                             k = 0
                             num = i-1-start
                             jiange = (maxWidth-curr_length)//(i-1-start)
                         s = ''
                         for j in range(start,i):
                             s += new[j][0]
                             if len(s) == maxWidth:
                                 pass
                             else:
                                 if jiange == 0:
                                     pass
                                 else:
                                     if j < (start+num):
                                         s += ' '*((maxWidth-curr_length-k)//(num))
                                     else:
                                         s += ' '*jiange
                         res.append(s)
                     start = i
                     curr_length = new[i][1]
                 else:
                     curr_length += new[i][1]
         if start == len(new)-1:
             jiange = maxWidth - new[-1][1]
             s = ''
             s += new[-1][0]
             s += ' '*jiange
             res.append(s)
         else:
             i = len(new)-1
             if i-start == 0:
                 jiange = 0
             else:
                 jiange = (maxWidth-curr_length)/(i-start) if (maxWidth-curr_length)%(i-start) == 0 else (maxWidth-curr_length)//(i-start)
             jiange = int(jiange)
             s = ''
             for j in range(start,i+1):
                 s += new[j][0]
                 if len(s) == maxWidth:
                     pass
                 else:
                     if j != i:
                         s += ' '
                     else:
                         s += ' '*(maxWidth-len(s))
             res.append(s)
         return res

class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         res = []
         i, n = 0, len(words)
         while i < n:
             count = len(words[i])
             last = i+1
             while last < n and count + len(words[last]) + 1 <= maxWidth:
                 count += len(words[last]) + 1
                 last += 1
             diff = last-i-1
             temp = words[i]
             if last == n or diff == 0:
                 for j in range(i+1, last):
                     temp += " "
                     temp += words[j]
                 temp += " "*(maxWidth-len(temp))
             else:
                 m, re = divmod(maxWidth-count, diff)
                 for j in range(i+1, last):
                     temp += " "*m
                     if re > 0:
                         temp += " "
                         re -= 1
                     temp += " "
                     temp += words[j]
             i = last
             res.append(temp)
         return res


class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
 
         res = [[0]]
         result = []
         for word in words:
             if len(word) + res[-1][-1] + (len(res[-1])-1) <= maxWidth:
                 res[-1].insert(-1, word)
                 res[-1][-1] += len(word)
             else:
                 res.append([word, len(word)])
 
         for index, i in enumerate(res):
             if index != len(res)-1 and (len(i)-2) != 0:
                 for j in range((maxWidth - i[-1]) % (len(i)-2)):
                     i[j] = i[j] + " "
 
         for index, i in enumerate(res):
             if index != len(res) - 1 and (len(i)-2) != 0:
                 result.append((" " * ((maxWidth - i[-1]) // (len(i)-2))).join(i[:-1]))
             else:
                 result.append(" ".join(i[:-1]) + " " * (maxWidth - i[-1] - (len(i)-2)))
         return result

class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         if len(words) == 0:
             return []
         res = []
         currFill = 0
         start = -1
         for i in range(len(words) + 1):
             if i < len(words) and len(words[i]) + currFill <= maxWidth:
                 if currFill == 0:
                     start = i
                 currFill += len(words[i]) + 1
             else:
                 currFill -= 1;
                 extra = maxWidth - currFill
                 numwords = i - start
                 spaces = [1 for _ in range(numwords)]
                 if numwords == 1 or i == len(words):
                     spaces[-1] = extra
                 else:
                     spaces[-1] = 0
                     for k in range(len(spaces) - 1):
                         spaces[k] += extra // (numwords - 1) + (1 if k < extra % (numwords - 1) else 0)
                 curr = ''
                 for k in range(len(spaces)):
                     curr += words[k + start] + ' ' * spaces[k]
                 res.append(curr)
                 currFill = len(words[i]) + 1 if i < len(words) else 0
                 start = i
         return res
                 
             
             


class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         if maxWidth == 0:
             return [" ".join(words)]
         words = words[:]
         results = []
         while words:
             run = []
             c = 0
             while words:
                 pad = 1 if run else 0
                 if len(words[0]) + pad + c > maxWidth:
                     spaces = maxWidth - sum([len(w) for w in run])
                     if len(run) == 1:
                         line = "".join(run + [" "] * spaces)
                         assert len(line) == maxWidth
                         results.append(line)
                     else:
                         eachSpace = spaces // (len(run) - 1)
                         extraSpaces = spaces % (len(run) - 1)
                         line = []
                         for i in range(len(run)):
                             line.append(run[i])
                             if i != len(run) - 1:
                                 line.append(' ' * eachSpace)
                                 if extraSpaces > 0:
                                     line.append(' ')
                                     extraSpaces -= 1
                         line = "".join(line)
                         assert len(line) == maxWidth, len(line)
                         results.append(line)
                     break
                 else:
                     if run:
                         c += 1
                     w = words.pop(0)
                     run.append(w)
                     c += len(w)
         if run:
             line = " ".join(run)
             line += ' ' * (maxWidth - len(line))
             results.append(line)
         return results


def justify_line(line, max_width):
     line_length = sum((len(i) for i in line))
     space_left = max_width - line_length
     if len(line) == 1:
         spaced_line = [line[0], " " * space_left]
     else:
         spaced_line = [line[0]]
         (spaces_per_word, remainder) = divmod(space_left, len(line) - 1)
         for i in range(1, len(line)):
             num_spaces = spaces_per_word
             if remainder > 0:
                 num_spaces += 1
                 remainder -= 1
             spaced_line.append(" " * num_spaces)
             spaced_line.append(line[i])
     return "".join(spaced_line)
 
 class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         lines = []
         i = 0
         line = []
         line_length = 0
         while i < len(words):
             if line_length != 0:
                 line_length += 1
             line_length += len(words[i])
             if line_length <= maxWidth:
                 line.append(words[i])
                 i += 1
             else:
                 lines.append(justify_line(line, maxWidth))
                 line = []
                 line_length = 0
         if line:
             final_line = " ".join(line)
             final_line += " " * (maxWidth - len(final_line))
             lines.append(final_line)
         return lines

class Solution:
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         
         acc = 0 # number of letters
         tmp, res = [], []
         for w in words:
             if acc + len(w) + len(tmp) > maxWidth:
                 # make up a line
                 for i in range(maxWidth - acc):
                     tmp[i%(len(tmp)-1 or 1)] += ' ' # need or 1 for the case: one word in tmp [to] --> "to    "
                 res.append(''.join(tmp))
                 acc = 0
                 tmp = []
                 
             tmp.append(w)
             acc += len(w)
             
         # the last element
         return res + [' '.join(tmp).ljust(maxWidth)]
                 


class Solution(object):
     def fullJustify(self, words, maxWidth):
         """
         :type words: List[str]
         :type maxWidth: int
         :rtype: List[str]
         """
         res, line, length_of_line = [], [], 0
         for word in words:
             if length_of_line + len(word) + len(line) > maxWidth:
                 #build a line to be printed, and append into res
                 for idx in range(maxWidth - length_of_line):
                     #add a blank to which word in a line
                     word_idx = idx % ((len(line) - 1) or 1)
                     line[word_idx] += ' '
                 res.append(''.join(line))
                 line, length_of_line = [], 0
             length_of_line += len(word)
             line.append(word)
         return res + [' '.join(line).ljust(maxWidth)]