In this post, you will learn how to write a python program to check for a palindrome string using recursion with a detailed explanation but before writing a program you should know about what is palindrome string.

What is a Palindrome string?

If a string is same as its reverse then that string is known as a palindrome string. for example REFER.

Algorithm

  1. Take two pointer L & R.
  2. L point to the first character of the string and R point to the last character of the String.
  3. if L >= R then returns True (means it is a palindrome)
  4. if S[L] != S[R] then returns False ( means it is not palindrome).
  5. otherwise return recursive functionis_palindrome(L+1, R-1,S) .

Now we understood how to implement the palindrome program using recursion with help of an algorithm.

But before writing a program you should now about:

  1. if-else
  2. function in python &
  3. How recursion works.

Source code

def is_palindrome(l,r,S):
    if l>=r:
        return True
    if S[l] != S[r]:
        return False
    return is_palindrome(l+1,r-1,S)

my_string = input('Enter your string: ')
l = 0
r = len(my_string)-1

check = is_palindrome(l,r,my_string)

if check:
    print(f"{my_string} is palindrome")
else:
    print(f"{my_string} is not palindrome")

Output

Enter your string: refer
refer is palindrome

Explanation

Let’s understand how the palindrome program works with the help of an example.

NOTE: Here in this program we use two pointer approach.

Initially pointer L point to the first character of the string and pointer R point to the last character of the string.

Check If L and R both are the same (if S[L] == S[R]) then increment L by 1 (L+1) and decrement R by 1 (R-1).

Check again if L & R (if S[L] == S[R]) both are the same then perform the same task again increment L (L+1) and decrement R (R-1).

In this case L = R this means the given string is a palindrome.

This is how the palindrome program works in python.

you can also check it by taking a non-palindrome string for your understanding.

Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment