Skip to content
BytePatterns

Valid Palindrome

Strings: lesson 2 of 11

Two pointers walk inward and settle it in one pass.

Lesson 2 of 11 · 4 min

Valid Palindrome

Step 1 of 7

A palindrome reads the same both ways, so read it from both ends at once — no reversed copy needed.

The Idea

A palindrome reads the same from both ends, so check it from both ends. Put one pointer at the start, one at the end, and walk them toward each other.

One mismatch is a definite no. Meeting in the middle is a definite yes — no reversed copy, no extra memory.

Real-World Example

Barcode and account-number checkers run the same shape of test: read from the front and the back at once and bail the instant the two disagree. Scanning the whole code first, then comparing, wastes the half of the work you already knew was doomed.

The Code

def is_palindrome(s):
    left, right = 0, len(s) - 1
    while left < right:
        if not s[left].isalnum():      # skip junk from the left
            left += 1
        elif not s[right].isalnum():   # ...and from the right
            right -= 1
        elif s[left].lower() != s[right].lower():
            return False               # one mismatch is enough
        else:
            left, right = left + 1, right - 1
    return True

print(is_palindrome("RaceCar!"))   # True
print(is_palindrome("byte"))       # False

Python

Your turn

Fill in the blank.

def is_palindrome(s):
  left, right = 0, len(s) - 1
  while ___:
      if s[left] != s[right]:
          return False
      left, right = left + 1, right - 1
  return True

print(is_palindrome("abba"), is_palindrome("abca"))   # want True False

Mini quiz

1 / 3

What does the two-pointer palindrome check cost?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.