π 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 left
and right
.
Move left
forward and right
backward.
Repeat until left < right
.
This way, the string is reversed without using extra space.
βοΈ Algorithm
Initialize two variables: left = 0
and right = length - 1
.
While left < right
:
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.