Rearrange words in a sentence

August 31, 2022

array-and-hashmap

Problem URL: Rearrange words in a sentence

We will split the word with space as delimeter, sort them according to their length, join then again with space, finally return the capitalize string.

class Solution:
    def arrangeWords(self, text: str) -> str:
        arr = sorted(text.split(' '), key=len)
        res = " ".join(arr)
        return res.capitalize()

Time Complexity: O(nlog(n))
Space Complexity: O(n)