Reverse Words in a String (LeetCode 151): Solution and Explanation
Scan the string from right to left. Skip spaces, then read each word by walking left until a space or the start of the string, and append it to a list. The words arrive in reverse order, and joining them with a single space removes leading, trailing and repeated spaces.
Intuition
The answer wants the last word first. If you read the string from the right end, the first word you meet is the last word, so no separate reversal step is needed.
Extra spaces are the main trap. Instead of trying to copy some spaces and drop others, drop every space and put exactly one space between words when joining.
Two indices are enough to cut out a word: j remembers where it ends, and i walks left until it falls on a space or past index 0. The word is s[i + 1 .. j].
Approach: Right-to-left scan with a word list
- Set
i = len(s) - 1and create an empty listwords. - While
i >= 0, moveileft past any spaces. - If
idropped below 0, only spaces were left, so stop. - Set
j = i, then moveileft whiles[i]is not a space. - Append
s[i + 1 .. j]towords. - When the loop ends, return the words joined by a single space.
Step-by-step example
s = " hello world "
istarts at index 14. Indices 14 and 13 are spaces, soimoves to 12, thedof "world".j = 12.iwalks left overd,l,r,o,wand stops at index 7, a space. Appends[8..12] = "world".- Skip the space at index 7.
i = 6, theoof "hello". Setj = 6, walk left to index 1 and appends[2..6] = "hello". - Indices 1 and 0 are spaces, so
ibecomes -1 and the loop breaks. - Join
["world", "hello"]with one space to get"world hello".
Code: Python, Java, C++
1class Solution:
2 def reverseWords(self, s: str) -> str:
3 words = []
4 i = len(s) - 1
5 while i >= 0:
6 while i >= 0 and s[i] == ' ':
7 i -= 1
8 if i < 0:
9 break
10 j = i
11 while i >= 0 and s[i] != ' ':
12 i -= 1
13 words.append(s[i + 1:j + 1])
14 return " ".join(words)1class Solution {
2 public String reverseWords(String s) {
3 List<String> words = new ArrayList<>();
4 int i = s.length() - 1;
5 while (i >= 0) {
6 while (i >= 0 && s.charAt(i) == ' ') {
7 i--;
8 }
9 if (i < 0) {
10 break;
11 }
12 int j = i;
13 while (i >= 0 && s.charAt(i) != ' ') {
14 i--;
15 }
16 words.add(s.substring(i + 1, j + 1));
17 }
18 return String.join(" ", words);
19 }
20}1class Solution {
2public:
3 string reverseWords(string s) {
4 vector<string> words;
5 int i = (int)s.size() - 1;
6 while (i >= 0) {
7 while (i >= 0 && s[i] == ' ') {
8 i--;
9 }
10 if (i < 0) {
11 break;
12 }
13 int j = i;
14 while (i >= 0 && s[i] != ' ') {
15 i--;
16 }
17 words.push_back(s.substr(i + 1, j - i));
18 }
19 string out;
20 for (size_t k = 0; k < words.size(); k++) {
21 if (k > 0) out += ' ';
22 out += words[k];
23 }
24 return out;
25 }
26};Time and space complexity
O(n)
i only moves left, so every character is examined once, and the join copies each word character once more.
O(n)
The list of words and the output string together hold at most n characters.
Other approaches
Split, reverse, join (time O(n), space O(n))
Most languages can split on whitespace while discarding empty pieces, for example Python's s.split(). Reverse the list and join with a space. It is the shortest solution, but be careful: splitting on a single space character keeps empty strings for repeated spaces.
Reverse all, then reverse each word in place (time O(n), space O(1) extra)
With a mutable character array, reverse the whole string, reverse each word back, and compact the spaces with a write pointer. This uses O(1) extra space in languages with mutable strings, such as C++.
Deque of words (time O(n), space O(n))
Scan left to right, build each word, and push it to the front of a deque. Joining the deque gives the reversed order.
Common mistakes
- Splitting on a single space with
split(" ")produces empty strings for leading, trailing and repeated spaces, which then show up as extra spaces in the output. - Forgetting the check after skipping spaces. With leading spaces,
ican fall below 0 before another word starts, and reading a word from there would append an empty string. - Off-by-one when slicing. After the inner loop
ipoints at the space before the word (or -1), so the word starts ati + 1, noti. - Building the result with repeated string concatenation in a loop, which can become quadratic in languages with immutable strings.
Frequently asked questions
How are multiple spaces between words handled?
They are never copied. The scan skips every space and the join puts exactly one space between consecutive words, so any run of spaces becomes one space and leading or trailing spaces disappear.
Can this be done in O(1) extra space?
Only if the string is mutable, as in C++. Reverse the whole string, reverse each word, and shift characters left to squeeze out extra spaces. In Python, Java, JavaScript and Go, strings are immutable, so any solution needs O(n) space for the output.
How is this different from Reverse Words in a String III?
Problem 557 keeps the words in place and reverses the letters inside each word, with single spaces already guaranteed. Problem 151 keeps each word's letters as they are and reverses the order of the words, and it must also clean up irregular spacing.
Why scan from the right instead of splitting and reversing?
Both are O(n). Scanning from the right produces the words in final order in one pass and makes the space handling explicit, which is useful in interviews where built-in split may not be allowed.