Reverse String
Recursion
📋 Problem Statement
Write a recursive function reverse_string(s) that returns the reversed string. Input: "hello" → Output: "olleh". Input: "abc" → Output: "cba". You must use recursion — no loops or [::-1].
💡 Intuition
Reversing recursively: recurse to the end of the string, then append characters in reverse order as the stack unwinds. The -th call places s[i] after all characters from index onward.
🔧 Approach
- Use an index parameter (default 0) to track position.
- Base case: if
index == len(str), return"". - Recursive case: return
reverse_string(str, index + 1) + str[index]. - This recurses to the end first, then appends characters in reverse on the way back.
⚡ Complexity Analysis
Time
recursive calls, but total due to string concatenation creating a new string at each level
Space
for the recursion call stack
⚠️ Common Mistakes
- Using
[::-1]slicing — correct but defeats the purpose of learning recursion - Not understanding how the concatenation order creates the reversal
- String concatenation in Python creates new strings — total; use a list + join for production
- Forgetting the base case, causing infinite recursion
🎯 Final Thoughts
The pattern of "recurse to the end, then build on the way back" appears in tree traversals and many recursive algorithms. Understanding the call stack unwinding is key to grasping how this reversal works.