Open In App

JavaScript Program to Check for Palindrome String using Recursion

Last Updated : 08 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:


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:


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.


Output
Yes, it is palindrome

Next Article

Similar Reads