💡
Exercise 23

Valid Palindrome 15 XP Easy

LeetCode Ctrl+Enter Run Ctrl+S Save

LeetCode #125: Valid Palindrome — Another classic two-pointer problem.

A string is a palindrome if it reads the same forwards and backwards, considering only alphanumeric characters and ignoring case.

Examples:

  • "A man, a plan, a canal: Panama" → True (amanaplanacanalpanama)
  • "race a car" → False
  • " " → True (empty after filtering)

💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠

Complexity: Time O(n), Space O(1) — no extra string created!

📋 Instructions
Implement `isPalindrome(s)` using two pointers. - Skip non-alphanumeric characters - Compare case-insensitively - Return True/False
Two pointers: one at start, one at end. Move them inward. Skip non-alphanumeric characters. Compare lowercase versions. If mismatch → not a palindrome.
⚠️ Try solving it yourself first — you'll learn more!
def isPalindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        # Skip non-alphanumeric
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1
        # Compare
        if s[left].lower() != s[right].lower():
            return False
        left += 1
        right -= 1
    return True
🧪 Test Cases
Input
isPalindrome("A man, a plan, a canal: Panama")
Expected
True
Boolean check
Input
isPalindrome("race a car")
Expected
False
Boolean check
Input
isPalindrome(" ")
Expected
True
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.