Solution Review: Check Palindrome

This review provides a detailed analysis of the solution to check whether a string is a palindrome or not.

We'll cover the following

Solution: Using Recursion

Press + to interact
def isPalindrome(testVariable) :
# Base Case
if len(testVariable) <= 1 : # Strings that have length 1 or 0 are palindrome
return True
# Recursive Case
length = len(testVariable)
if testVariable[0] == testVariable[length - 1] : # compare the first and last elements
return isPalindrome(testVariable[1: length - 1])
return False
# Driver Code
print(isPalindrome("madam"))

Explanation

Our base case will be the condition when we have a string of size 11 or less. In such a case, we can return True directly.

For the recursive case, we will compare the first and last elements. If they are same, we will call the function isPalindrome() for the string again, but with the first and last elements removed.

The illustration below shows how we reached our algorithm:

Finally, let’s have a look at the sequence of function calls:


In the next lesson, we have a short quiz on recursion with strings to test your concepts.