← Algorithm Practice Track

Palindrome Checks with Two Pointers

Palindrome Checks with Two Pointers

Two pointers are ideal when you need to compare elements from both ends.

Template for string palindrome checks

def is_palindrome(s):
    left, right = 0, len(s) - 1

    while left < right:
        while left < right and not s[left].isalnum():
            left += 1
        while left < right and not s[right].isalnum():
            right -= 1

        if s[left].lower() != s[right].lower():
            return False

        left += 1
        right -= 1

    return True

Benefits

  • O(n) time
  • O(1) additional space
  • Works well with normalized string comparisons

This exact pattern solves Valid Palindrome.

Practice Problems