We compare characters from both ends of the string, recursing inward. If all paired characters match, the string is a palindrome.
- Clean the string: keep only alphanumeric characters, convert to lowercase.
- Define a helper with
leftandrightindices. - Base case: If
left >= right, return True. - If characters at
leftandrightdon't match, return False. - Recurse with
left + 1andright - 1.
- Time Complexity: O(N).
- Space Complexity: O(N) (recursion stack + cleaned string).
def is_palindrome(s):
cleaned = ''.join(c.lower() for c in s if c.isalnum())
def helper(left, right):
if left >= right:
return True
if cleaned[left] != cleaned[right]:
return False
return helper(left + 1, right - 1)
return helper(0, len(cleaned) - 1)