Reverse Words in a String
Medium
Topics
Given an input string s, reverse the order of the words. Words are separated by one or more spaces; the result must have single spaces between words and no leading or trailing spaces.
Example 1
Input: s = "the sky is blue" Output: "blue is sky the"
Example 2
Input: s = " hello world " Output: "world hello"
Constraints
- 1 <= s.length <= 10^4
Editorial — intuition, approach, complexity and pitfalls
Intuition
Three things happen at once: split on runs of whitespace, reverse the order, and normalise the separators to a single space. A split that collapses runs and drops empty fields does the first and third for free, which is why the one-liner is the honest answer in a language that has one.
In an interview the follow-up is to do it in place on a character array, which is the two-step trick: reverse the entire array, then reverse each word back. That turns the ordering problem into two local reversals and needs no extra buffer.
Approach
- Split on whitespace, discarding empty fields.
- Reverse the resulting list.
- Join with a single space.
Dry Run
"the sky is blue" -> "blue is sky the"
" hello world " -> "world hello" leading and trailing space dropped
"a good example" -> "example good a" the run of three spaces collapses
the in-place variant on a char array
reverse everything "elpmaxe doog a"
reverse each word back "example good a"
then compact the runs "example good a"Complexity
- Time — O(n): split, reverse and join are each linear.
- Space — O(n) for the word list and the result. The char-array variant is O(1) auxiliary beyond the array itself.
Common Pitfalls
- Splitting on a single space literal rather than on whitespace runs. On
"a good example"that yields empty fields and the join reproduces them, giving"example good a"instead of"example good a". - Trimming the ends but not collapsing interior runs, which passes the first example and fails the third.
- Reversing the characters of each word as well as the order of the words. Only the word order reverses.
- Claiming O(1) space while using
split. The word list is O(n); the in-place version is the one that earns the O(1) claim, and only on a mutable array. - In the in-place variant, reversing the words first and the whole array second. The order matters: whole array first, then each word.
Full Solution — all languages
class Solution:
def reverseWords(self, s):
return " ".join(reversed(s.split()))import java.util.*;
class Solution {
public String reverseWords(String s) {
String[] parts = s.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = parts.length - 1; i >= 0; i--) {
if (parts[i].isEmpty()) continue;
if (sb.length() > 0) sb.append(' ');
sb.append(parts[i]);
}
return sb.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string reverseWords(string s) {
vector<string> words;
stringstream ss(s);
string w;
while (ss >> w) words.push_back(w);
string res;
for (int i = (int)words.size() - 1; i >= 0; i--) {
if (!res.empty()) res += " ";
res += words[i];
}
return res;
}
};/**
* @param {string} s
* @return {string}
*/ var reverseWords = function(s) {
return s.split(/\s+/).filter(x => x.length).reverse().join(' ');
};