SDE & MLE Prep

151. Reverse Words in a String

Problem

Return the words of s in reverse order, joined by single spaces. s may have leading, trailing or repeated spaces, which must not appear in the output.

Example: " hello world " → "world hello"

Constraints: follow-up: O(1) extra space if strings are mutable.

Split on whitespace (drops extra spaces), reverse, join. In-place follow-up (char array): reverse the whole string, then reverse each word, then compact spaces.

Complexity: O(n).

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(reversed(s.split()))