Reverse Words in a String
01 · Problem
You are given a string s made of words separated by spaces. A word is any maximal run of non-space characters.
Return a new string containing the same words in reverse order, joined by exactly one space. The input may have leading spaces, trailing spaces, or several spaces between two words; none of that extra spacing should appear in the output (no leading or trailing spaces, no double spaces). The characters inside each word keep their original order.
02 · Examples
s = "code runs fast today"
"today fast runs code"
The four words are reversed and joined by single spaces.
s = " keep it simple "
"simple it keep"
Leading and trailing spaces are dropped from the result.
s = "data meets logic"
"logic meets data"
Each run of three spaces between words collapses to a single space.
03 · Constraints
- 011 <= s.length <= 104
- 02s contains English letters (upper and lower case), digits, and spaces ' '
- 03s contains at least one word
04 · Optimal complexity
- Time
- O(n)
- Space
- O(n)
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.