Check If String is Palindrome Using Recursion

Are you looking for recursive a program that checks whether a String is a Palindrome? In this article, I will show you how you can check if the string is palindrome using recursion.

What is Palindrome String?

A palindromic string is a string if read from head to end or end to head remains the same. Meaning if you reverse the string even then the string remains the same.

For example String “malayalam” is a palindrome as if you reverse this string you will get the same string. So, to efficiently check if the string is palindrome we can put two-pointer one at the start and one at the end.

Once pointers are placed you can start comparing each element of the first and last element until you reach mid of the string in which case it will be palindrome and if any of the characters do not match then it is not a palindrome.

Let us see an example code and the most efficient way to find if the string is palindrome or not here we are using the recursive method to determine if the string is a palindrome.

Recursive Palindrome Code to Check the String

// C++ program to check if the given string is palindrome
#include <iostream>
using namespace std;

bool isPalindrome(const string &givenString, int start, int end)
{
  //Check if start index is more than end index then return True
  // Since we reached the end of the string.
    if (start >= end)   
        return true;
  //If any time while iterating through string 
  //if two elements of start and end index do not match
  // then return false.
    if (givenString[start] != givenString[end])
        return false;
  
  //Otherwise keep checking the elements of string 
  //by decreasing and increasing end and start index value.
    return isPalindrome(givenString, ++start, --end);   
}

int main ()
{
  string isPalin = "malayalam";
  int size = isPalin.size()-1;
  bool val = isPalindrome(isPalin, 0,size);
  if(val) cout<<"String is Palindrome";
  else cout<<"String is not Palindrome";
    return 0;
}

Output:

Check If String is Palindrome Using Recursion

If you liked our post related to how to find if the string is palindrome using recursion in c++ then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. System Pause C++ Command Guide

Leave a Comment