beginner

Check Palindrome

Check if a string is a palindrome.

Palindrome detection is a fundamental algorithmic problem that teaches string comparison, reversal techniques, and optimization strategies. This exercise will help you master string manipulation while understanding different algorithmic approaches.

📚 Concepts & Theory

A palindrome is a word, phrase, or sequence that reads the same backward as forward, like "racecar" or "madam". Checking for palindromes is a classic string manipulation problem that combines string reversal with comparison logic.

Understanding Palindrome Logic:

  • Compare the string with its reverse

  • If they match, it's a palindrome

  • Case sensitivity matters: "Racecar" ≠ "racecaR"
Approach 1: Using String Reversal
def is_palindrome(text):
return text == text[::-1]

Approach 2: Two-Pointer Technique
Compare characters from both ends moving inward:

def is_palindrome(text):
left, right = 0, len(text) - 1
while left < right:
if text[left] != text[right]:
return False
left += 1
right -= 1
return True

Approach 3: Using reversed()

def is_palindrome(text):
return list(text) == list(reversed(text))

The two-pointer technique is more space-efficient as it doesn't create a reversed copy. For case-insensitive checking, convert to lowercase first: text.lower().

🎯 Your Challenge

Write is_palindrome that returns True/False.

📝 Starter Code

Python
def is_palindrome(text):
    pass

print(is_palindrome('radar'))
  • A palindrome reads the same forwards and backwards
  • Try reversing the string and comparing
  • The [::-1] slice can reverse a string
  • Don't forget: empty strings and single characters are palindromes

Solution

Python
def is_palindrome(text):
    text = text.lower().replace(' ', '')
    return text == text[::-1]

print(is_palindrome('radar'))

Explanation

This solution compares the original string with its reversed version using Python's slicing syntax [::-1]. If they are identical, the string reads the same forwards and backwards, making it a palindrome. This is the most concise and Pythonic approach. Time complexity: O(n) for creating the reversed string and O(n) for comparison, total O(n). Space complexity: O(n) for storing the reversed string.

⚠️ Common Mistakes to Avoid

  • Not handling case sensitivity ("Racecar" vs "racecar")
  • Forgetting to handle spaces in phrases ("race car")
  • Comparing with wrong direction (result + char)
  • Not considering empty strings (which are palindromes)

❓ Frequently Asked Questions

In this basic version, no. 'A' and 'a' are different. For case-insensitive palindromes, convert to lowercase first with text.lower().
This basic version includes them. Advanced palindrome checks remove non-alphanumeric characters first.
Yes! An empty string reads the same forwards and backwards.
The two-pointer technique is most space-efficient (O(1) space) while slicing uses O(n) space but is more readable.

🔗 Related Exercises