Reverse the Order of Words in a Sentence

Implement reverseWords

Given a string s, return a new string with the words in reverse order — separated by a single space, with no leading or trailing spaces, even if s itself had extra spaces between words or around the edges. Splitting the string into a words array and reading it backward works, but it allocates an array you only ever read once. Scanning from the end of the string and extracting one word at a time — skip spaces, capture the word, repeat — builds the answer in a single backward pass with no intermediate array.

Example 1:

Input: s = " the sky is blue "

Output: "blue is sky the"

Example 2:

Input: s = "hello world"

Output: "world hello"

Example 3:

Input: s = "a good example"

Output: "example good a"

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ s.length ≤ 10⁴
  • s contains English letters, digits, and spaces ' '
  • There is at least one word in s
  • s may have leading, trailing, or multiple spaces between words

s =

the sky is blue