array and hashmap September 6, 2022

Reverse words in a string

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

We will strip the extra space and then split the string with space. Finally, we reverse the words, combine them to a string and return.

class Solution:
    def reverseWords(self, s: str) -> str:
        words = s.strip().split()

        return " ".join(reversed(words))

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