Reverse Words in a String
Reverse Words in a String is LeetCode 151 (Medium). You are given a string s of words separated by spaces. Return the words in reverse order, separated by single spaces.
- Word: a run of characters that are not spaces. The letters inside a word keep their order.
- Messy spacing:
smay start or end with spaces and may have several spaces between two words. The answer must have exactly one space between words and none at either end.
s has at most 10⁴ characters, so one pass over it is enough.
- 1 <= s.length <= 10⁴
- s contains English letters (upper-case and lower-case), digits, and spaces ' '.
- There is at least one word in s.
Intuition
Once the words are in a list, reversing their order is one call. The real work is the spacing: extra spaces must vanish, and a careless split turns every extra space into an empty word.
So split on runs of spaces, not on a single space. The split then returns only the real words, whatever the spacing was. Reverse that list and join it with exactly one space, and the output spacing comes out right whatever the input looked like.
When a string problem is about words, not characters, turn the string into a list of words first. A split that treats any run of spaces as one gap removes the spacing cases before the main logic starts.
Approach
Before reading on, write down what " a good example ".split(" ") returns in Python, and how many of those pieces are empty. Aim for O(n) time.
Two ways to solve it
Let the split remove every extra space, then reverse the list of words.
- Code: three short lines in any language.
- Memory: a list of words plus the new string.
- Risk: low; the split handles all the spacing.
The answer to give unless O(1) space is asked for.
Change the characters of s itself, with no list of words.
- Compact: move the words left, one space between them.
- Reverse all: the words end up in reverse order, spelled backwards.
- Fix words: reverse each word again so it reads forwards.
The follow-up; O(1) extra space only where strings are mutable.
Both are O(n) time, and in Python and Java the string has to be copied either way, so the shorter split method wins and the steps, code and demo follow it. The in-place code for the follow-up comes further down.
Split into words
Use a split that treats any run of spaces as one gap and ignores spaces at both ends: s.split() in Python, s.trim().split("\\s+") in Java, or reading with >> from an istringstream in C++.
Reverse the list
Reverse the order of the words, not their letters. Each word is kept exactly as it is; only its position changes, so the last word comes first.
Join with single spaces
Join the list with one space. That puts exactly one space between neighbouring words and none before the first or after the last, so no trimming is needed afterwards.
Code in Python, C++ and Java
split() with no argument treats any run of spaces as one gap and ignores spaces at the ends, so it returns only the words.the runs until the next space, so it becomes word 1.sky runs until the next space, so it becomes word 2.is runs until the next space, so it becomes word 3.blue runs until the next space or the end of the string, so it becomes word 4.blue, becomes the first.is comes next, counting from the end, so it takes place 2.sky comes next, counting from the end, so it takes place 3.the comes next, counting from the end, so it takes place 4."blue is sky the".split() with no argument treats any run of spaces as one gap and ignores spaces at the ends, so it returns only the words.hello runs until the next space, so it becomes word 1.world runs until the next space, so it becomes word 2.split() adds no empty string for them.world, becomes the first.hello comes next, counting from the end, so it takes place 2."world hello".split() with no argument treats any run of spaces as one gap and ignores spaces at the ends, so it returns only the words.a runs until the next space, so it becomes word 1.good runs until the next space, so it becomes word 2.example runs until the next space or the end of the string, so it becomes word 3.example, becomes the first.good comes next, counting from the end, so it takes place 2.a comes next, counting from the end, so it takes place 3."example good a".In-place reversal
First move the words to the front with one space between them, then reverse the whole string, then reverse each word back so it reads forwards. Python and Java copy the string into a list or char[] first, because their strings cannot be changed.
Common pitfalls
Splitting on a single space
words = s.split(" ")words = s.split()
"a b ".split(" ") gives ['a', '', 'b', '']. The empty strings survive the reverse and the join, and come out as extra spaces in the answer.
Reversing the characters instead of the words
return s[::-1]
return " ".join(s.split()[::-1])
Reversing the whole string also spells every word backwards (blue becomes eulb). The unit to reverse is the word, so split first.
Complexity
Reverse Words in a String FAQ
What is the Python one-liner?
" ".join(s.split()[::-1]). It splits on runs of spaces, reverses the list and joins it with single spaces, all in one line.
How does the Java solution handle spaces?
It splits with String[] words = s.trim().split("\\s+"), then Collections.reverse(Arrays.asList(words)) and String.join(" ", words). Keep the trim(): without it, a string that starts with a space splits into an empty first word, which becomes a stray space at the end of the answer.
What is the difference between LeetCode 151 and LeetCode 557?
LeetCode 151 reverses the order of the words and fixes the spacing: "the sky" becomes "sky the". LeetCode 557 (Reverse Words in a String III) keeps the word order and reverses the letters inside each word: "the sky" becomes "eht yks".