Reverse Words in a String - Problem

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note: s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Input & Output

Example 1 — Basic Case with Extra Spaces
$ Input: s = "the sky is blue"
Output: "blue is sky the"
💡 Note: Words are ["the", "sky", "is", "blue"], reversed gives ["blue", "is", "sky", "the"], joined with spaces: "blue is sky the"
Example 2 — Leading and Trailing Spaces
$ Input: s = " hello world "
Output: "world hello"
💡 Note: After trimming spaces, words are ["hello", "world"], reversed gives ["world", "hello"], result: "world hello"
Example 3 — Multiple Spaces Between Words
$ Input: s = "a good example"
Output: "example good a"
💡 Note: Multiple spaces are treated as single delimiters, words ["a", "good", "example"] become ["example", "good", "a"]

Constraints

  • 1 ≤ s.length ≤ 104
  • s contains English letters (upper-case and lower-case), digits, and spaces ' '
  • There is at least one word in s

Visualization

Tap to expand
Reverse Words in a StringTransform irregular spacing and reverse word orderInput:" hello world "Irregular spaces, leading/trailing whitespaceREVERSE WORDShelloworldswap orderworldhelloOutput:"world hello"Clean single spaces
Understanding the Visualization
1
Input
String with words separated by irregular spaces
2
Process
Extract words and reverse their order
3
Output
Words in reverse order with single spaces
Key Takeaway
🎯 Key Insight: Split by whitespace to handle irregular spacing, reverse word array, then join with single spaces
Asked in
Microsoft 45 Amazon 38 Google 32 Apple 28
125.0K Views
High Frequency
~15 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen