JavaScript Program to Check for Palindrome String using Recursion
Last Updated :
26 Aug, 2023
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:
Javascript
function checkPalindrome(str, s, e) {
if (s == e)
return true ;
if ((str.charAt(s)) != (str.charAt(e)))
return false ;
if (s < e + 1)
return checkPalindrome(str, s + 1, e - 1);
return true ;
}
function isPalindrome(str) {
let len = str.length;
if (len == 0)
return true ;
return checkPalindrome(str, 0, len - 1);
}
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:
Javascript
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)
Share your thoughts in the comments
Please Login to comment...