JavaScript Program to Check for Palindrome String using Recursion
Given a string, write a recursive function that checks if the given string is a palindrome, else, not a palindrome. A string is called a palindrome if the reverse of the string is the same as the original one. For example – “madam”, “racecar”, etc.
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. In the recursive program, the solution to the base case is provided and the solution to the bigger problem is expressed in terms of smaller problems.
Examples:
Input : NITIN
Output : Yes
Reverse of NITIN is also NITIN.
Input : CAR
Output : No
Reverse of CAR is not CAR it is RAC
Approach 1:
- If there is only one character in the string, return true.
- Else compare the first and last characters and recuring for the remaining substring.
Example:
// A recursive JavaScript program to
// check whether a given String
// is palindrome or not
function checkPalindrome(str, s, e) {
// If there is only one character
if (s == e)
return true;
// If first and last characters
// does not match
if ((str.charAt(s)) != (str.charAt(e)))
return false;
// If there are more than
// two characters, check if
// middle substring is also
// palindrome or not.
if (s < e + 1)
return checkPalindrome(str, s + 1, e - 1);
return true;
}
function isPalindrome(str) {
let len = str.length;
// An empty string is
// considered as palindrome
if (len == 0)
return true;
return checkPalindrome(str, 0, len - 1);
}
// Driver Code
let str = "malayalam";
if (isPalindrome(str))
console.log("Yes, it is palindrome");
else
console.log("No,it is not palindrome");
Output
Yes, it is palindrome
Approach 2:
- In this approach, we will check while traversing whether the ith and n-i-1th index are equal or not.
- If there are not equal return false and if they are equal then continue with the recursion calls.
Example:
function checkPalindrome(s, i) {
if (i > s.length / 2) { return true; }
return s[i] == s[s.length - i - 1] && checkPalindrome(s, i + 1)
}
let str = "racecar";
let ans = checkPalindrome(str, 0);
if (ans == true) {
console.log("Yes,it is palindrome");
}
else {
console.log("No,it is not palindrome");
}
Output
Yes,it is palindrome
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 3: Using Substring Comparison
In this approach, we will use the substring method to compare the first and last characters, and recursively check the middle substring.
Example: This example shows the implementation of the above-mentioned approach.
function isPalindrome(str) {
if (str.length <= 1) {
return true;
}
if (str[0] !== str[str.length - 1]) {
return false;
}
return isPalindrome(str.substring(1, str.length - 1));
}
let str = "deified";
if (isPalindrome(str)) {
console.log("Yes, it is palindrome");
} else {
console.log("No, it is not palindrome");
}
Output
Yes, it is palindrome