Reverse Words in a String III — Problem & Solution
Reverse Words in a String III solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Reverse Words in a String III is an easy coding problem on strings and two pointers, asked in Amazon, Meta and Zoho interviews.
- Difficulty: Easy
- Topics: Strings, Two Pointers
- Asked at: Amazon, Meta, Zoho
- 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 a string s, reverse the characters of each word while keeping the words in their original order and preserving the single spaces between them.
Example 1
Input: s = "Let us code"
Output: teL su edoc
Example 2
Input: s = "God Ding"
Output: doG gniD
Example 3
Input: s = "a"
Output: a
Constraints
1 <= s.length <= 60s contains printable ASCII letters and single spaces between words.There are no leading or trailing spaces.
Hints for Reverse Words in a String III
Hint 1
Split on the single space, reverse each piece, join back with a space.
Hint 2
Because the spacing is guaranteed simple, no trimming or collapsing is needed.
How to solve Reverse Words in a String III
Split on the single space, reverse each word independently, and rejoin.
Approach
- Split
son" ". - Reverse the characters of each piece.
- Join the pieces with a single space.
Why it works
The spacing is guaranteed to be exactly one space between words with none at the ends, so splitting and rejoining preserves the layout while the per-word reversal does the required work.
Complexity
- Time —
O(n) - Space —
O(n)
Pitfalls
- An in-place two-pointer reverse per word avoids the intermediate list.
- Do not use a whitespace-collapsing split here — it would silently change the spacing.
Reference solution
Python
def reverseWords(s: str) -> str:
return " ".join(word[::-1] for word in s.split(" "))Java
public static String reverseWords(String s) {
String[] pieces = s.split(" ", -1);
StringBuilder out = new StringBuilder();
for (int i = 0; i < pieces.length; i++) {
if (i > 0) out.append(' ');
out.append(new StringBuilder(pieces[i]).reverse());
}
return out.toString();
}C++
string reverseWords(string s) {
int i = 0;
int n = (int) s.size();
while (i < n) {
int j = i;
while (j < n && s[j] != ' ') j++;
reverse(s.begin() + i, s.begin() + j);
i = j + 1;
}
return s;
}JavaScript
var reverseWords = function(s) {
return s.split(" ").map(function(w) {
return w.split("").reverse().join("");
}).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