Palindrome check (recursion)
Easy TimeO(n) SpaceO(n)
A palindrome reads the same forwards and backwards, like "racecar". Given a string s, return true when it is one and false when it is not. The comparison is character by character, and a string of length 0 or 1 is a palindrome.
Examples
Example 1
- Input
- s = "racecar"
- Output
truerandr,aanda,candc, withealone in the middle.
Example 2
- Input
- s = "hello"
- Output
falsehat the front andoat the back are different characters.
The Code
function isPalindrome(s) {
function check(lo, hi) {
if (lo >= hi) return true;
if (s[lo] !== s[hi]) return false;
return check(lo + 1, hi - 1);
}
return check(0, s.length - 1);
}
isPalindrome("racecar");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.