class Solution:
def reorderSpaces(self, text: str) -> str:
""" tc O(N) sc O(M) N: len of text, M: number of words
"""
cnt = 0
for c in text:
if c == ' ':
cnt += 1
tmp = text.split()
#edge case: there is only one word, unknown space
if len(tmp)== 1:
return tmp[0] + ' '*cnt
#print(tmp)
space = cnt//(len(tmp)-1) # here assuming len(tmp) - 1 != 0 ===> edge case
extra = cnt%(len(tmp)-1)
res = []
for each in tmp:
res.append(each)
res.append(' '*space)
res[-1] = extra * ' '
return ''.join(res)