Reverse a string (recursion)
Easy TimeO(n²) (slice + concat copies) SpaceO(n)
Given a string s, return it reversed: "hello" becomes "olleh". No loops, and no calling reverse(). Characters keep their identity and only the order changes, so a string of length 0 or 1 is already its own reverse.
Examples
Example 1
- Input
- s = "hello"
- Output
- The same five characters, last to first.
"olleh"
Example 2
- Input
- s = ""
- Output
- Nothing to turn around, and the empty string comes back.
""
The Code
function reverseString(s) {
if (s.length <= 1) return s;
return reverseString(s.slice(1)) + s[0];
}
reverseString("hello");Done
More like this
All recursion examples (13) →- Fibonacci The classic branching recursion — every call spawns two more.
- Factorial The simplest linear recursion — one call, one multiply.
- Tower of Hanoi Move a stack of disks by trusting the recursion for the rest.
- GCD (Euclid) Euclid’s algorithm — recursion that shrinks fast.
- Power Raise a number to a power one multiply at a time.
- Sum of digits Peel one digit off at a time with the modulo trick.