📌 Introduction
Reversing a string is one of the most common Data Structures and Algorithms (DSA) problems asked in coding interviews. While it sounds simple, the challenge here is to reverse the string without using extra space — meaning we should not create another string or array to store the reversed version.
This tests your understanding of in-place algorithms, memory usage, and pointer manipulation (especially in C or C++).
🧠 Problem Statement
Given a string, write a program to reverse it in-place (without using extra space).
Example
Input:
"hello"Output:
"olleh"
📝 Approach (Step-by-Step)
We can solve this using the two-pointer technique:
Place one pointer at the beginning of the string (
left).Place another pointer at the end of the string (
right).Swap the characters at
leftandright.Move
leftforward andrightbackward.Repeat until
left < right.
This way, the string is reversed without using extra space.
⚙️ Algorithm
Initialize two variables:
left = 0andright = length - 1.While
left < right:Swap
string[left]andstring[right].Increment
left, decrementright.
Stop when
left >= right.
💻 Implementation in C
#include <stdio.h>#include <string.h>
void reverseString(char str[]) {
int left = 0;
int right = strlen(str) - 1;
char temp;
while (left < right) {
// Swap characters
temp = str[left];
str[left] = str[right];
str[right] = temp;
// Move pointers
left++;
right--;
}
}
int main() {
char str[] = "hello";
printf("Original String: %s\n", str);
reverseString(str);
printf("Reversed String: %s\n", str);
return 0;
}
🔍 Dry Run Example
For str = "hello":
| Step | Left | Right | String State |
|---|---|---|---|
| 1 | 0 | 4 | oellh |
| 2 | 1 | 3 | olleh |
| 3 | 2 | 2 | Stop |
Final result = "olleh" ✅
⏱️ Time & Space Complexity
Time Complexity: O(n), since each character is swapped at most once.
Space Complexity: O(1), since we did not use any extra string or array.
🎯 Key Takeaways
The two-pointer technique is one of the most efficient ways to reverse a string.
This approach is in-place, which means it doesn’t use additional memory.
Commonly asked in coding interviews to test your problem-solving skills.
🏁 Conclusion
Reversing a string without extra space is a classic DSA problem that teaches us about pointer manipulation, memory optimization, and in-place algorithms. By mastering this, you also strengthen your foundation for more advanced string problems like palindrome checks, string rotation, and substring matching.
Join the conversation! Your thoughts help the community grow.