AI Hints
Home›DSA in Python Tutorial›Array Practice
DSA in Python · Lesson 17 of 132

Practice: Palindromes

Reads the same both ways.

⏱ 2 min read▶ Video at 19:30🎓 Free
Watch this lesson in the DSA in Python courseWatch on YouTube ↗Full DSA in Python course

A palindrome reads the same forwards and backwards. Like racecar, or level. Real sentences have spaces, capitals, and punctuation, so we must ignore those. Pause, and try to write it with two pointers.

Practice: Palindromes
From the video: Practice: Palindromes
  • Same both ways
  • racecar, level
  • Ignore spaces and punctuation

Two pointers, skipping junk

Left and right start at each end. If a character isn't a letter or a digit, we skip past it. Then we compare the two characters, ignoring case. One mismatch, and it's not a palindrome. Run it. A man, a plan, a canal, Panama, is a palindrome. Hello is not.

palindrome.pypython
def is_palindrome(text):
    left, right = 0, len(text) - 1
    while left < right:
        if not text[left].isalnum():
            left += 1
        elif not text[right].isalnum():
            right -= 1
        elif text[left].lower() != text[right].lower():
            return False
        else:
            left, right = left + 1, right - 1
    return True

print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("Hello"))
Output
True
False

The short version

Python can also do it in two lines. Keep only letters and digits, in lower case, and compare the result with its reverse. Run it. Same answers. It's easier to read, but it builds new strings, so it uses O of N extra memory, while the two pointer version uses O of one.

palindrome_short.pypython
def is_palindrome(text):
    clean = [c.lower() for c in text if c.isalnum()]
    return clean == clean[::-1]

print(is_palindrome("A man, a plan, a canal: Panama"))
print(is_palindrome("Hello"))
Output
True
False

Summary

Two pointers check a palindrome with no extra memory, skipping characters that don't count. The short version is clearer, but uses more memory. Next, strings, and why building them carelessly is slow.

Key takeaways
  • Skip non-letters
  • Compare lower case
  • Short version: O(n) space
Next up: Strings Are Immutable — building strings efficiently