Reverse Words in a String III
Easy
Topics
Given a string s of words separated by single spaces, reverse the characters of each word while preserving word order and spacing.
Example 1
Input: s = "Lets code" Output: "steL edoc"
Example 2
Input: s = "God Ding" Output: "doG gniD"
Constraints
- 1 <= s.length <= 5*10^4
- Words are separated by single spaces with no leading/trailing spaces.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Each word is reversed where it sits; the word order and the spacing are untouched. So split on spaces, reverse each token, and join back. Because the constraints promise single spaces with no leading or trailing whitespace, the split-and-join round trip reproduces the original layout exactly.
The in-place alternative, which is what to offer if asked for O(1) extra space: scan for word boundaries and reverse each span with two pointers, on a mutable character buffer. Same O(n) time, no allocation beyond the buffer.
Approach
- Split on a single space.
- Reverse each token.
- Join with a single space.
Dry Run
s = "Let's take LeetCode contest"
tokens ["Let's", "take", "LeetCode", "contest"]
reversed ["s'teL", "ekat", "edoCteeL", "tsetnoc"]
joined "s'teL ekat edoCteeL tsetnoc"Complexity
- Time — O(n): every character is visited a constant number of times across the split, the reversals and the join.
- Space — O(n): the token list and the output string. The two-pointer in-place version is O(1) beyond a mutable buffer, and is the better answer when space is the question.
Common Pitfalls
- Splitting on whitespace generally rather than on a single space.
split()with no argument collapses runs and drops empty tokens, which would alter the spacing if the input ever had any — here the constraints forbid it, so both happen to work. - Reversing the word order as well. That is a different problem; here only the letters within each word move.
- Joining with the wrong separator, or using
joinon a generator twice. - Claiming O(1) space for the split version.
Full Solution — all languages
class Solution:
def reverseWords(self, s):
return " ".join(w[::-1] for w in s.split(" "))import java.util.*;
class Solution {
public String reverseWords(String s) {
String[] parts = s.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) sb.append(' ');
sb.append(new StringBuilder(parts[i]).reverse());
}
return sb.toString();
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: string reverseWords(string s) {
stringstream ss(s);
string w, res;
bool first = true;
while (ss >> w) {
reverse(w.begin(), w.end());
if (!first) res += " ";
res += w;
first = false;
}
return res;
}
};/**
* @param {string} s
* @return {string}
*/ var reverseWords = function(s) {
return s.split(' ').map(w => w.split('').reverse().join('')).join(' ');
};