Reverse Words in a String
Problem
Given a string s, return a string with the words in reverse order, where words are defined as sequences of non-space characters separated by spaces.
- 1 ≤ s.length ≤ 10⁴
- s contains English letters (upper-case and lower-case), digits, and spaces ' '
- There is at least one word in s
Example
s = "the sky is blue""blue is sky the"The straightforward approach is to split the string into words by spaces, reverse the order of these words, and then join them back with a single space. For example, splitting "the sky is blue" yields ["the", "sky", "is", "blue"]. Reversing this list gives ["blue", "is", "sky", "the"]. Joining with spaces produces "blue is sky the".
Approach
Straightforward Solution
A naive approach might manually parse the string character by character to extract words and then reverse them. This is error-prone and verbose.
Core Observation
The problem reduces to reversing the order of words in a string, where words are separated by spaces. The key is to correctly identify words and handle multiple spaces and leading/trailing spaces.
Path to Optimal
Using built-in string methods simplifies the problem. The split() method automatically handles multiple spaces and trims leading/trailing spaces by returning only the words. Reversing the list of words and joining them with a single space yields the desired output efficiently.
Optimal Approach
Split the string into words using s.split(), which returns a list of words ignoring extra spaces. Reverse this list in-place using list.reverse(), then join the reversed words with a single space using ' '.join(words). This approach is concise, efficient, and leverages Python's optimized string methods.
Time
O(n)
Splitting the string scans all characters once, reversing the list is O(w) where w is the number of words (w ≤ n), and joining the words is O(n). Overall linear in the length of the input string.
Space
O(n)
The split operation creates a list of words that in total contain all characters of the input string, so auxiliary space is proportional to input size.
Pattern Spotlight
String Manipulation (Word Splitting and Reversal)
When reversing word order in a string, use built-in split to tokenize words cleanly, reverse the token list, and join with a single space to handle spacing and ordering elegantly.
Solution
| 1 | class Solution: |
| 2 | def reverseWords(self, s: str) -> str: |
| 3 | words = s.split() |
| 4 | words.reverse() |
| 5 | return " ".join(words) |
Step-by-Step Solution
Split Input String into Words
| 3 | words = s.split() |
Objective
To extract all words from the input string, ignoring extra spaces.
Key Insight
The built-in split() method splits the string on whitespace and automatically discards empty strings caused by multiple spaces or leading/trailing spaces. This yields a clean list of words without manual parsing.
Interview Quick-Check
Core Logic
Using s.split() returns a list of words by splitting on any whitespace and ignoring empty tokens, which simplifies word extraction.
Common Pitfalls & Bugs
Manually splitting by ' ' without handling multiple spaces can lead to empty strings in the list, causing incorrect output.
Reverse the List of Words In-Place
| 4 | words.reverse() |
Objective
To reverse the order of the extracted words efficiently.
Key Insight
Reversing the list in-place with list.reverse() is an O(w) operation that avoids creating a new list, making it memory efficient. This step reorders the words to their final reversed sequence.
Interview Quick-Check
Core Logic
Reversing the list of words changes their order from original to reversed, which is the core requirement of the problem.
Complexity
In-place reversal is O(w) time and O(1) auxiliary space, where w is the number of words.
Join Reversed Words into Output String
| 5 | return " ".join(words) |
Objective
To concatenate the reversed words into a single string separated by spaces.
Key Insight
Using ' '.join(words) efficiently concatenates the list of words with a single space delimiter, ensuring the output string has exactly one space between words and no leading or trailing spaces.
Interview Quick-Check
Core Logic
Joining the reversed words with a single space produces the final reversed word order string with correct spacing.
Common Pitfalls & Bugs
Using string concatenation in a loop would be inefficient due to repeated string copying.
Line Analysis
This solution has 1 Critical line interviewers watch for.
words = s.split()
Split the input string into a list of words by whitespace.
This line leverages Python's built-in split() method, which automatically handles multiple spaces and trims leading/trailing spaces, producing a clean list of words essential for correct reversal.
words.reverse()
Reverse the list of words in-place.
Reversing the list in-place efficiently reorders the words without extra memory allocation, directly achieving the core transformation required by the problem.
return " ".join(words)
Join the reversed words into a single string separated by spaces and return it.
Joining with a single space ensures the output string has exactly one space between words and no leading or trailing spaces, fulfilling the problem's formatting requirements.
Test Your Understanding
Why is using s.split() preferable to manually parsing the string for words?
Because s.split() automatically handles multiple spaces and trims leading/trailing spaces, simplifying the logic and reducing the chance of bugs, while providing efficient tokenization.
Don't just read it. Drill it.
Reconstruct Reverse Words in a String from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Reverse Words in a String drill