Reverse Words in a String

Problem Given a string of length N, reverse it word by word — the order of the words is reversed, but the characters within each word stay as they are.

Input / Output

  • Input: string str, possibly with irregular spacing
  • Output: a string with the words in reverse order, separated by exactly one space, with no leading or trailing spaces

Constraints

  • Input may contain leading/trailing spaces and multiple consecutive spaces between words
  • Output must normalise all whitespace to single spaces
  • 1 <= |str| <= 10^4

Example

  • Input: " the sky is blue " → Output: "blue is sky the"
  • Tricky cases: a string of only spaces " " → ""; a single word "hello" → "hello" unchanged
asked …
LeaderboardSalaryAccount