Write a recursive function that returns the reverse of a string. Assume the string contains only ASCII characters.
reverse(s)
reverse("hello") // → "olleh"
reverse("a") // → "a"
reverse("") // → ""
Reversing a string with a loop usually means walking from the end backward. Recursively, you approach it from the front: what has to be true of the reversed string in terms of a smaller, already-reversed piece?
What's the shortest string where "reversed" and "original" are the same thing? A string with zero or one character reads the same forwards and backwards — nothing to rearrange. That's the floor the recursion strips toward.
Split the string into its first character and everything after it. Trust that a recursive call correctly reverses "everything after the first character." To reverse the whole string, that first character needs to end up last — since whatever came first in the original now comes last in the reverse. So: reverse the rest, then stick the first character on the end.
Reversing "abc" calls itself on "bc", then "c", then "" — the base case, which returns "" immediately. Unwinding: the call holding "c" appends "c" to "", returning "c". The call holding "bc" reverses "c" (getting "c") and appends "b", returning "cb". The call holding "abc" reverses "bc" (getting "cb") and appends "a", returning "cba". Each character gets appended on the way back up, in the reverse order it was peeled off going down.
This isn't a coincidence of append order — it's a direct translation of the definition: the reverse of a string is the reverse of its tail, followed by its head. Worth being honest about the cost too: each call creates a new string via concatenation, so a stack n calls deep uses more time and memory than an iterative two-pointer swap would. That's a fine tradeoff for a warm-up exercise whose real purpose is practicing the base-case/recursive-case pattern on sequence data — a pattern you'll reuse constantly once problems get harder than plain loops can handle.
def reverse(s):
if len(s) <= 1:
return s
return reverse(s[1:]) + s[:1]
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.