class Solution:
def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
stmtList = []
l = []
i=0
while i< len(words):
n = len("".join(l))
if len(l) > 1:
n+=len(l)-1
if (n + len(words[i])) >= maxWidth:
stmtList.append(l)
l=[words[i]]
else:
l.append(words[i])
i+=1
if len(l)>0:
stmtList.append(l)
stmtList = [s for s in stmtList if len(s)>0]
# print(stmtList)
res = []
for k in range(len(stmtList)):
l = stmtList[k]
s = ""
n = len(l)
wordsLen = sum([len(s) for s in l])
spacesLen = maxWidth - wordsLen
if n == 1:
s = l[0] + "".join([" " for i in range(spacesLen)])
elif k == (len(stmtList) - 1):
nSpaces = 0
for word in l:
s += word
if word != l[-1]:
nSpaces+=1
s += " "
s += "".join([" " for i in range(spacesLen-nSpaces)])
else:
spacesLenEach = spacesLen//(n-1)
# remaining = wordsLen - spacesLenEach * (n-1)
spacesLenEachFirst = spacesLenEach + 1#spacesLen%(n-1)
# print(spacesLenEach, spacesLenEachFirst)
for i in range(n):
s+=l[i]
if i<spacesLen%(n-1):
s+= "".join([" " for i in range(spacesLenEachFirst)])
elif i<(n-1):
s+= "".join([" " for i in range(spacesLenEach)])
res.append(s)
return res