array and hashmap August 31, 2022

Rearrange words in a sentence

Time O(nlog(n)) Space O(n) Open original problem

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)