Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Reverse String Recursively

Reverse text with recursive Python slicing. Students combine a reversed suffix with its first character and trace empty and single-character stopping cases.

AdvancedPhase 3 - Level 4: String-based RecursionExample 1 of 10
reverse-string-recursively.py
1def reverse_string(s):
2 # Base case
3 if len(s) <= 1:
4 return s
5
6 # Recursive case
7 return reverse_string(s[1:]) + s[0]
8
9# Test
10text = input("Enter a string: ")
11result = reverse_string(text)
12print(f"Reversed: {result}")

Output

Enter a string: Hello
Reversed: olleH

In this one

  • Reverse a suffix
  • Concatenate during return
  • Stop at short strings

How it works

  1. 1

    Return s when its length is at most one.

  2. 2

    Reverse the suffix s[1:] recursively.

  3. 3

    Append the saved first character after that result.

Edge cases

What happens for empty input?

What happens for empty input?

The empty string returns unchanged.

Are spaces reversed too?

Are spaces reversed too?

Yes. Every character position participates.

What's going on

reverse_string works on s[1:] first, then appends s[0] to the returned result. That moves the original first character to the end.

A string of length zero or one returns unchanged. For cat, pending concatenations produce t, then ta, then tac. Slices and strings are newly created values, and recursive calls use stack space; this is not an in-place reversal.

What happens for empty input? The empty string returns unchanged.

Are spaces reversed too? Yes. Every character position participates.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why append s[0] after the call?

Pick an answer to check it.

Question 2

What happens for empty input?

Pick an answer to check it.

Questions people ask

What happens for empty input?

The empty string returns unchanged.

Are spaces reversed too?

Yes. Every character position participates.

Why append s[0] after the call?

The first character belongs at the reversed end.