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 String INPUT Input String s: "the sky is blue" Words identified: the sky is blue [0] [1] [2] [3] Array after split(): ["the","sky","is","blue"] ALGORITHM STEPS 1 Trim whitespace Remove leading/trailing spaces from input 2 Split by spaces Use split() to create array of words 3 Reverse array Use reverse() method to flip word order 4 Join with space Use join(" ") to create final string s.trim() .split(/\s+/) .reverse() .join(" ") FINAL RESULT After reverse(): blue is sky the [0] [1] [2] [3] Output String: "blue is sky the" OK - SUCCESS Words reversed Single spaces only No extra whitespace Time: O(n) | Space: O(n) Key Insight: Using built-in split(), reverse(), and join() methods provides clean, readable code with optimal O(n) performance. The regex /\s+/ in split handles multiple spaces between words automatically, avoiding manual space handling. This approach leverages language optimizations and is preferred in interviews for its clarity and efficiency. TutorialsPoint - Reverse Words in a String | Built-in Split and Join Approach
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