Reverse Words in a String — Solution in Python, Java & C++
Reverse Words in a String solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. A medium problem.
Reverse Words in a String is a medium coding problem on strings and two pointers, asked in Amazon, Microsoft, Meta and Bloomberg interviews.
- Difficulty: Medium
- Topics: Strings, Two Pointers
- Asked at: Amazon, Microsoft, Meta, Bloomberg, Snapchat, Yelp, HCL, Virtusa
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an input string s, reverse the order of the words.
A word is a maximal run of non-space characters. The words in s may be separated by more than one space. The returned string must have the words in reverse order joined by a single space, with 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
Explanation: The surrounding spaces are dropped.
Example 3
Input: s = "a good example"
Output: example good a
Explanation: Runs of spaces collapse to one.
Constraints
1 <= s.length <= 60s consists of lowercase English letters and spaces.There is at least one word in s.
Hints for Reverse Words in a String
Hint 1
Split on whitespace and discard the empty pieces that runs of spaces produce.
Hint 2
Reverse the list of words, then join with a single space.
Hint 3
The in-place variant reverses the whole string, then reverses each word again.
How to solve Reverse Words in a String
Tokenise on whitespace — which also discards the empty pieces produced by multiple spaces — reverse the token list, and join with single spaces.
Approach
- Split the string on runs of whitespace, dropping empty pieces.
- Reverse the list of words.
- Join with a single space.
Why it works
Splitting on whitespace runs normalises the spacing for free: leading, trailing and repeated spaces all vanish, leaving only the words. Reversing and rejoining then produces exactly the required format.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- Splitting on a single space keeps empty strings for repeated spaces; either filter them or split on runs.
- The O(1)-extra-space variant reverses the whole array, then reverses each word in place, then compacts the spaces.
Reference solution
Python
def reverseWords(s: str) -> str:
return " ".join(reversed(s.split()))Java
public static String reverseWords(String s) {
String[] pieces = s.split(" ");
List<String> words = new ArrayList<>();
for (String w : pieces) {
if (w.length() > 0) words.add(w);
}
Collections.reverse(words);
return String.join(" ", words);
}C++
string reverseWords(string s) {
vector<string> words;
string cur = "";
for (char ch : s) {
if (ch == ' ') {
if (!cur.empty()) { words.push_back(cur); cur = ""; }
} else {
cur += ch;
}
}
if (!cur.empty()) words.push_back(cur);
string out = "";
for (int i = (int) words.size() - 1; i >= 0; i--) {
if (!out.empty()) out += " ";
out += words[i];
}
return out;
}JavaScript
var reverseWords = function(s) {
const words = s.split(" ").filter(function(w) { return w.length > 0; });
words.reverse();
return words.join(" ");
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings · Two Pointers Technique