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 reads the same both ways, so the first character must equal the last, the second the second-last, and so on. 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

time, space.

How to spot it

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

Common mistakes

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

Practise the ideas first

Practise it

Go further