Algorithm LogbookAlgorithm Logbook

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 ii-th call places s[i] after all characters from index i+1i+1 onward.

🔧 Approach

  1. Use an index parameter (default 0) to track position.
  2. Base case: if index == len(str), return "".
  3. Recursive case: return reverse_string(str, index + 1) + str[index].
  4. This recurses to the end first, then appends characters in reverse on the way back.

Complexity Analysis

Time

O(N)O(N) recursive calls, but O(N2)O(N^2) total due to string concatenation creating a new string at each level

Space

O(N)O(N) 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 — O(N2)O(N^2) 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.