Sentence Reverser - Problem

Given a string containing words separated by spaces, reverse the order of the words while keeping each word intact.

For example, if the input is "hello world programming", the output should be "programming world hello".

Note: Words are separated by single spaces, and there are no leading or trailing spaces in the input.

Input & Output

Example 1 — Basic Case
$ Input: sentence = "hello world code"
Output: "code world hello"
💡 Note: The words are reversed in order: 'hello' becomes last, 'world' stays in middle, 'code' becomes first
Example 2 — Two Words
$ Input: sentence = "good morning"
Output: "morning good"
💡 Note: Simple swap: 'good' and 'morning' switch positions
Example 3 — Single Word
$ Input: sentence = "programming"
Output: "programming"
💡 Note: Only one word, so the result is the same as input

Constraints

  • 1 ≤ sentence.length ≤ 104
  • sentence contains only letters and spaces
  • No leading or trailing spaces
  • Words are separated by single spaces

Visualization

Tap to expand
INPUTALGORITHMRESULT"hello world code"helloworldcode1Split by spacesBreak into word array2Reverse orderFlip array positions3Join with spacesCombine back to string"code world hello"codeworldhelloKey Insight:Built-in split and reverse functions handle the tedious character work automaticallyTutorialsPoint - Sentence Reverser | Split and Reverse
Asked in
Google 25 Amazon 30 Microsoft 20
32.0K Views
Medium Frequency
~15 min Avg. Time
850 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