C++ Program to Reverse String Using Recursion
void reverseString(string &str, int start, int end) that swaps characters at start and end and calls itself with updated indices until they meet or cross.Examples
How to Think About It
Algorithm
Code
#include <iostream> #include <string> using namespace std; void reverseString(string &str, int start, int end) { if (start >= end) return; swap(str[start], str[end]); reverseString(str, start + 1, end - 1); } int main() { string s = "hello"; reverseString(s, 0, s.length() - 1); cout << s << endl; return 0; }
Dry Run
Let's trace the string "hello" through the recursive reverse function.
Initial call
reverseString("hello", 0, 4) swaps 'h' and 'o' -> "oellh"
Second call
reverseString("oellh", 1, 3) swaps 'e' and 'l' -> "olleh"
Third call
reverseString("olleh", 2, 2) start equals end, recursion stops
| Call | Start Index | End Index | String State |
|---|---|---|---|
| 1 | 0 | 4 | oellh |
| 2 | 1 | 3 | olleh |
| 3 | 2 | 2 | olleh |
Why This Works
Step 1: Base Case
The recursion stops when the start index is greater than or equal to the end index, meaning the string is fully reversed or has one character left.
Step 2: Swapping Characters
Each recursive call swaps the characters at the current start and end positions to move characters to their reversed positions.
Step 3: Recursive Call
The function calls itself with updated indices moving inward, gradually reversing the entire string.
Alternative Approaches
#include <iostream> #include <string> using namespace std; string reverseString(const string &str) { if (str.empty()) return ""; return reverseString(str.substr(1)) + str[0]; } int main() { string s = "hello"; cout << reverseString(s) << endl; return 0; }
#include <iostream> #include <string> using namespace std; void reverseString(string &str) { int n = str.length(); for (int i = 0; i < n / 2; i++) { swap(str[i], str[n - i - 1]); } } int main() { string s = "hello"; reverseString(s); cout << s << endl; return 0; }
Complexity: O(n) time, O(n) space
Time Complexity
The function swaps pairs of characters moving inward, so it runs in linear time proportional to the string length.
Space Complexity
Recursion uses stack space proportional to half the string length, so space complexity is O(n).
Which Approach is Fastest?
The iterative approach is fastest and uses constant space, while recursive methods use extra stack space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive in-place swap | O(n) | O(n) | Learning recursion and in-place reversal |
| Recursive new string | O(n^2) | O(n^2) | Simple code but inefficient for large strings |
| Iterative swap | O(n) | O(1) | Best for performance and memory efficiency |