JuniorCodeCommonNot answered yet
Reverse word order while keeping every space in place
Reverse the ORDER of words in a string but keep the spaces exactly where they were. With _ for spaces: __hello_my___dear__world_ → __world_dear___my__hello_.
Requirements:
- The space pattern is fixed; only the word tokens move. Handle empty, all-spaces, no-spaces.
std::string reverseWordsKeepSpaces(const std::string& s) {
// your code here
}
Write the implementation.
Extract the word tokens in order. Then walk the original string: copy spaces unchanged, and for each maximal non-space run pour in the next word taken from the END of the token list. The space gaps stay fixed; only the words are reversed. O(n).
- ✗Normalizing spaces (the classic reverse-words) instead of keeping the exact pattern
- ✗Mishandling leading or trailing spaces
- ✗Breaking on a string of only spaces or with no spaces at all
- →Why does the classic split-and-join approach fail this variant?
- →How would you do it in place to avoid extra allocation?
Contents
Task
Reverse the word order while keeping all spaces in place.
Solution
std::string reverseWordsKeepSpaces(const std::string& s) {
std::vector<std::string> words;
std::string cur;
for (char c : s) {
if (c == ' ') { if (!cur.empty()) { words.push_back(cur); cur.clear(); } }
else cur += c;
}
if (!cur.empty()) words.push_back(cur);
std::string out = s;
int w = words.size() - 1;
size_t i = 0;
while (i < out.size()) {
if (out[i] == ' ') { ++i; continue; }
const std::string& word = words[w--];
for (char ch : word) out[i++] = ch; // non-space slot
}
return out;
}
Key points
- Take words from the end of the list and pour them into non-space slots.
- Leave the spaces untouched — only words move.
- Edge cases: empty, all spaces, no spaces.
Contents