Android & iPhone apps are coming soon. Log in for a plan and reminders made for you →

BeginnerTwo Pointers

Checking a palindrome with two pointers

Compare the first and last characters, then step both inward. No reversed copy needed, and skipping junk characters is easy.

The idea

A palindrome reads the same both ways, so the first character must equal the last, the second the second-last, and so on. Two pointers walking inward check exactly those pairs.

Unlike reversing the string, you can skip characters that don't count (spaces, punctuation) as you go.

Worked example

“race a car” (letters and digits only, ignoring case)

  1. r = r ✓, a = a ✓, c = c ✓, e vs a ✗ → not a palindrome.

In code (Python)

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

O(n) time, O(1) space.

How to spot it

  • “palindrome”, “reads the same forwards and backwards”, “reverse in place”.

Common mistakes

  • Forgetting to lower-case before comparing.
  • Moving both pointers when only one landed on a character to skip.

Practise it

Go further