JavaScript Program to Check Palindrome Using Recursion
function isPalindrome(str) { if (str.length <= 1) return true; if (str[0] !== str[str.length - 1]) return false; return isPalindrome(str.slice(1, -1)); } which compares the first and last characters and calls itself on the middle substring.Examples
How to Think About It
Algorithm
Code
function isPalindrome(str) { if (str.length <= 1) return true; if (str[0] !== str[str.length - 1]) return false; return isPalindrome(str.slice(1, -1)); } console.log(isPalindrome("racecar")); // true console.log(isPalindrome("hello")); // false console.log(isPalindrome("a")); // true
Dry Run
Let's trace the string "racecar" through the code
Initial call
str = "racecar", first = 'r', last = 'r', they match, call isPalindrome("aceca")
Second call
str = "aceca", first = 'a', last = 'a', they match, call isPalindrome("cec")
Third call
str = "cec", first = 'c', last = 'c', they match, call isPalindrome("e")
Base case
str = "e", length is 1, return true
Return back
All previous calls return true, final result is true
| Call | String | First Char | Last Char | Result |
|---|---|---|---|---|
| 1 | racecar | r | r | recurse with aceca |
| 2 | aceca | a | a | recurse with cec |
| 3 | cec | c | c | recurse with e |
| 4 | e | e | e | true (base case) |
Why This Works
Step 1: Check base case
If the string length is 0 or 1, it means we have checked all pairs or the string is empty, so it is a palindrome.
Step 2: Compare characters
Compare the first and last characters of the string. If they differ, the string is not a palindrome.
Step 3: Recursive call
If the first and last characters match, call the function again on the substring that excludes these two characters to check the rest.
Alternative Approaches
function isPalindromeIterative(str) { for (let i = 0; i < str.length / 2; i++) { if (str[i] !== str[str.length - 1 - i]) return false; } return true; } console.log(isPalindromeIterative("racecar")); // true
function isPalindromeReverse(str) { return str === str.split("").reverse().join(""); } console.log(isPalindromeReverse("racecar")); // true
Complexity: O(n) time, O(n) space
Time Complexity
The function compares pairs of characters from the outside moving inward, making about n/2 comparisons, so time is O(n).
Space Complexity
Each recursive call adds a new stack frame, and slicing the string creates new substrings, so space is O(n).
Which Approach is Fastest?
The iterative approach is fastest and uses less memory because it avoids recursion and substring creation.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Learning recursion and simple code |
| Iterative | O(n) | O(1) | Performance and memory efficiency |
| Built-in reverse | O(n) | O(n) | Quick and simple for small strings |