Reverse Words in a Sentence
You are given a sentence as a string. The sentence contains one or more words separated by single spaces, with no leading or trailing spaces. Return a new…
You are given a sentence as a string. The sentence contains one or more words separated by single spaces, with no leading or trailing spaces. Return a new string in which the order of the words is reversed, while each word's characters remain intact. For example, reversing the sentence `"morning coffee break"` yields `"break coffee morning"`.
- `1 <= s.length <= 1000` - Words consist only of printable ASCII letters and digits. - Words are separated by exactly one space. - There are no leading or trailing spaces in the input. - The reversed sentence must also use single spaces and have no leading or trailing spaces. - The interactive visualizer accepts at most 9 words; longer valid judge inputs are execution-only.
Example 1: input s = "the sky is blue"; output "blue is sky the". Splitting on spaces gives ["the","sky","is","blue"]. Reversed: ["blue","is","sky","the"]. Joined: "blue is sky the".
Example 2: input s = "good morning"; output "morning good". Two words swap positions: "morning" moves to the front and "good" moves to the back.
Example 3: input s = "hello"; output "hello". A single-word sentence has nothing to reorder — the output is identical to the input.
Category: Strings. Topic: strings. Difficulty: Easy. Patterns: string-processing.