JuniorCodeCommonNot answered yet
Reverse the characters of each word, keeping word order
Given a string of words separated by spaces, reverse the characters within each word while preserving word order and all spacing. For example "QUICK FOX" → "KCIUQ XOF". Edit in place.
Requirements:
- O(n) time, O(1) extra space.
- Preserve runs of multiple spaces and leading/trailing spaces exactly.
void reverseEachWord(std::string& s) {
// your code here
}
Write the implementation.
Walk the string; at the start of each maximal non-space run, find its end, then reverse that run in place with two pointers swapping inward. Spaces are skipped and left untouched, so all spacing is preserved. One pass, O(n) time, O(1) extra space.
- ✗Normalizing or collapsing spaces when the spec requires preserving them exactly
- ✗Reversing across spaces and merging adjacent words
- ✗Allocating a new buffer when an in-place O(1)-space solution is expected
- →How do you preserve double spaces while reversing only the word characters?
- →How would you also reverse the order of the words?
Contents
Task
Reverse the characters of each word in place, keeping word order and all spacing, in O(n) time and O(1) space.
Solution
void reverseEachWord(std::string& s) {
size_t i = 0, n = s.size();
while (i < n) {
if (s[i] == ' ') { ++i; continue; } // leave spaces alone
size_t j = i;
while (j < n && s[j] != ' ') ++j; // end of word
std::reverse(s.begin() + i, s.begin() + j);
i = j;
}
}
Key points
- Spaces are skipped and stay in place — word order and gaps are preserved.
- Each word is reversed in place with two pointers (
std::reverse). - One pass, O(n) time, O(1) extra space.
Contents