Python Program to Reverse a String Using Recursion
def reverse_string(s): return s if len(s) == 0 else reverse_string(s[1:]) + s[0] which calls itself with the string minus the first character and adds the first character at the end.Examples
How to Think About It
Algorithm
Code
def reverse_string(s): if len(s) == 0: return s else: return reverse_string(s[1:]) + s[0] print(reverse_string('hello'))
Dry Run
Let's trace the string 'abc' through the recursive reverse_string function.
Initial call
reverse_string('abc') calls reverse_string('bc') and will add 'a' later.
Second call
reverse_string('bc') calls reverse_string('c') and will add 'b' later.
Third call
reverse_string('c') calls reverse_string('') and will add 'c' later.
Base case
reverse_string('') returns '' because string is empty.
Returning from third call
reverse_string('c') returns '' + 'c' = 'c'.
Returning from second call
reverse_string('bc') returns 'c' + 'b' = 'cb'.
Returning from initial call
reverse_string('abc') returns 'cb' + 'a' = 'cba'.
| Call | String | Returned Value |
|---|---|---|
| 1 | abc | calls reverse_string('bc') + 'a' |
| 2 | bc | calls reverse_string('c') + 'b' |
| 3 | c | calls reverse_string('') + 'c' |
| 4 | returns '' | |
| 3 | c | returns 'c' |
| 2 | bc | returns 'cb' |
| 1 | abc | returns 'cba' |
Why This Works
Step 1: Base case stops recursion
When the string is empty (len(s) == 0), the function returns the empty string to stop further calls.
Step 2: Recursive call reduces problem size
The function calls itself with the string minus the first character (s[1:]), making the problem smaller each time.
Step 3: Building reversed string on return
After the recursive call returns, the function adds the first character (s[0]) to the end, gradually building the reversed string.
Alternative Approaches
def reverse_string(s): return s[::-1] print(reverse_string('hello'))
def reverse_string(s): result = '' for char in s: result = char + result return result print(reverse_string('hello'))
Complexity: O(n) time, O(n) space
Time Complexity
The function calls itself once per character, so it runs in linear time proportional to the string length.
Space Complexity
Each recursive call adds a layer to the call stack, so space used is proportional to the string length.
Which Approach is Fastest?
Using slicing (s[::-1]) is fastest and uses less memory, but recursion is good for learning and understanding.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursion | O(n) | O(n) | Learning recursion and problem solving |
| Slicing | O(n) | O(1) | Fastest and simplest in Python |
| Loop | O(n) | O(1) | When avoiding recursion and slicing |