Reverse Words in a String
Difficulty: Medium
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 that 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.
Example
Input: s = " the sky is blue "
Output: "blue is sky the"
Explanation: After reversing the word order and trimming extra spaces: "blue is sky the".
Brute-force approach
Split the string by spaces, filter out empty entries, reverse the list of words, and join with a single space.
Steps
- Split the string by whitespace
- Filter out empty strings
- Reverse the word list
- Join with single space
Time complexity: O(n) · Space complexity: O(n)
Trade-offs
- Uses O(n) extra space for the word list
- Relies on built-in split — interviewers may ask for in-place
- Some languages create intermediate string copies during split
Optimal approach
Key insight: Reversing the entire string puts words in the right order but with reversed characters. Reversing each word individually fixes the characters.
For an in-place approach: (1) reverse the entire string, (2) reverse each individual word, (3) clean up extra spaces. This avoids the word list allocation.
Steps
- Trim leading/trailing spaces, collapse multiple spaces
- Reverse the entire character array
- Iterate through, reverse each word individually
- Return the result string
Time complexity: O(n) · Space complexity: O(1)