JuniorCodeVery commonNot answered yet
Implement string reversal
Reverse a string in-place — modify the passed string so its characters appear in reverse order.
Requirements:
- O(n) time, O(1) extra space (swap toward the centre; do not allocate a new buffer).
- Handle the empty string and a single-character string.
#include <string>
void reverseString(std::string& s) {
// your code here
}
Write the implementation.
Use two indices (or iterators) from both ends and swap characters toward the centre. O(n) time, O(1) space in-place. std::reverse from <algorithm> does this in one line.
- ✗Returning a new reversed string when in-place was requested (wastes O(n) memory)
- ✗Not handling empty string or single-character string edge cases
- ✗Naive reversal on UTF-8 strings — must work with codepoints, not bytes
- →How would you reverse words in a sentence without reversing the characters in each word?
- →How do you reverse a UTF-8 encoded string correctly?
Contents
Task
Implement in-place string reversal.
Solution
void reverseString(std::string& s) {
int l = 0, r = static_cast<int>(s.size()) - 1;
while (l < r) { std::swap(s[l++], s[r--]); }
}
// Or simply: std::reverse(s.begin(), s.end());
Key points
- Two-pointer swap: O(n) time, O(1) space.
std::reverseis the idiomatic C++ one-liner.- Naive byte reversal is incorrect for multi-byte UTF-8 codepoints.
Contents