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
PreviewUsing built-in string methods simplifies the problem. The split() method automatically handles multiple spaces and trims leading/trailing spaces by returning only the words…
Full step-by-step walkthrough on Pro →
Optimal Approach
PreviewSplit the string into words using s.split(), which returns a list of words ignoring extra spaces…
Full step-by-step walkthrough on Pro →
Want the full reasoning chain?
Unlock the complete walkthrough, line-by-line analysis, and recall drill.
Unlock ProTime
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
To reverse the order of the extracted words efficiently.
Join Reversed Words into Output String
To concatenate the reversed words into a single string separated by spaces.
2 more steps with full analysis available on Pro.
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.
Full line-by-line criticality + rationale for all 3 lines available on Pro.
Test Your Understanding
Why is using s.split() preferable to manually parsing the string for words?
See the answer with Pro.
Related Problems
Two Pointers pattern
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