Reverse a string with recursion, find the base case, and see why slicing in each call makes it O(n²). Practise recursive thinking in Python.
The problem
Return s reversed, using recursion (no loops, no [::-1]).
Examples
Example 1
Input
reverse_rec('hello')Expected output
'olleh'
Example 2
Input
reverse_rec('ab')Expected output
'ba'
+ 2 hidden tests on Submit.
Edge cases to ask about
- Empty string
- Single character
Hints
0/3How an interviewer scores this
0/9Your code runs in real CPython inside your browser — nothing is sent anywhere. The first run downloads the interpreter (about 6 MB, once). Your code is saved on this device as you type.
Complexity Lab
What does this cost as n grows?
Interviewers score the analysis as much as the code. Commit to an answer first — then check it, and read why.
Pick both to reveal the answer.
From brute force to optimal
The progression an interviewer wants to hear, one step at a time.
| Approach | Time | Space | Idea |
|---|---|---|---|
| reverse(s[1:]) + s[0] | O(n²) | O(n²) | Each slice and concatenation copies the string. |
| bestRecurse on indices into a list | O(n) | O(n) | Swap ends and recurse inward — no copies. |
Walkthrough of the optimal approach (try it yourself first)
reverse(s) = reverse(s[1:]) + s[0], with strings of length ≤ 1 as the base case.
It is elegant but O(n²): every call slices a new string. The O(n) recursive version passes indices into a list and swaps the ends. And Python's recursion limit makes either impractical past ~1000 characters — say so.
Complexity: O(n²) time, O(n²) space. There are n calls and each slices a new string of up to n characters, so the copying adds up to O(n²).
Reveal the reference solution
def reverse_rec(s): if len(s) <= 1: return s return reverse_rec(s[1:]) + s[0]
Follow-ups interviewers ask
- Make it O(n) with index arguments.
Frequently asked interview questions
Core interview concepts, complexities, and follow-ups scored by hiring teams.
What is the time complexity of Reverse a String Recursively in Python?
The optimal solution runs in O(n²) time and O(n²) auxiliary space. There are n calls and each slices a new string of up to n characters, so the copying adds up to O(n²).
What is the brute-force approach, and how do you optimise it?
reverse(s[1:]) + s[0]: O(n²) time, O(n²) space. Each slice and concatenation copies the string. Recurse on indices into a list: O(n) time, O(n) space. Swap ends and recurse inward — no copies.
What follow-up questions do interviewers ask about Reverse a String Recursively?
Make it O(n) with index arguments.
