Introduction
Reversing a string is one of the most common interview and coding test questions in C++ programming. The goal is simple — you are given a string, and you must reverse its characters so that the first becomes last, the second becomes second last, and so on.
However, the challenge here is to reverse the string in-place, meaning you should not use any extra memory (like creating another string or array). Instead, you modify the existing string directly in memory.
What Does In-Place Mean?
“In-place” means that we do not use extra data structures like another array, vector, or string to store the reversed result. The original string’s characters are rearranged within the same memory space.
This saves memory and improves efficiency — especially important for large strings or memory-constrained environments like embedded systems.
Logic Behind Reversing a String In-Place
The idea is simple:
Use two pointers — one starting from the beginning (
start), another from the end (end).Swap the characters at these positions.
Move both pointers toward the center.
Continue until
startbecomes greater than or equal toend.
This method modifies the string directly, with O(1) extra memory and O(n) time complexity.
Step-by-Step Implementation
Let’s look at the C++ code and break it down.
Example 1: Using Two Pointers
#include <iostream>
#include <string>
using namespace std;
void reverseString(string &str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
// Swap characters using a temporary variable
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
int main() {
string text = "Hello, World!";
reverseString(text);
cout << "Reversed String: " << text << endl;
return 0;
}
Output:
Reversed String: !dlroW ,olleH
✅ Explanation:
string &str— passed by reference to modify the original string.startandendrepresent the positions of characters to swap.The loop continues until all characters are reversed.
Example 2: Using std::swap() Function
C++ provides a built-in swap() function in the <utility> header, making the code cleaner.
#include <iostream>
#include <string>
#include <utility>
using namespace std;
void reverseString(string &str) {
int start = 0;
int end = str.length() - 1;
while (start < end) {
swap(str[start], str[end]);
start++;
end--;
}
}
int main() {
string s = "OpenAI GPT";
reverseString(s);
cout << "Reversed: " << s << endl;
return 0;
}
Output:
Reversed: TPG IAnepO
✅ Key Points:
Uses
swap()for simplicity.Still in-place, no extra memory used.
Join the conversation! Your thoughts help the community grow.