Search⌘ K

Solution Review: Check for a Palindrome

Explore how to implement a recursive function that checks if a string is a palindrome by comparing its first and last characters and reducing the problem size. This lesson helps you understand base and recursive cases, preparing you to solve string recursion problems confidently in coding interviews.

We'll cover the following...

Solution: Using Recursion

Python 3.5
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 is the condition when we have a string of size ...