151/670

151. Reverse Words in a String

Medium

You are given a string s made up of English letters, digits, and spaces. A word is any maximal run of non-space characters.

Return a new string containing the same words in reverse order, joined by single spaces. The result must have no leading or trailing spaces, even if s does, and any stretch of multiple spaces between words collapses to one.

Can you build the answer in one right-to-left scan, without a library split?

Example 1:

Input: s = "the sky is blue"

Output: "blue is sky the"

Explanation: The four words come back out in the opposite order.

Example 2:

Input: s = " hello world "

Output: "world hello"

Explanation: Leading and trailing spaces disappear — only the words survive.

Example 3:

Input: s = "a good example"

Output: "example good a"

Explanation: The triple space between "good" and "example" collapses to a single space in the answer.

Constraints:

  • 1 ≤ s.length ≤ 10⁴
  • s consists of English letters (upper and lower case), digits, and spaces ' '
  • s contains at least one word

Hints:

Splitting on whitespace already throws away the extra spaces for you — after that the task is just reversing a list of tokens and joining them back.

For the single-scan version: start a pointer at the right end, skip spaces until you hit the last character of a word, keep moving until you pass its first character, then copy that slice out. Repeat until the pointer falls off the left edge.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "the sky is blue"

Expected output: "blue is sky the"