Skip to main content
09

Valid Palindrome

Easytwo pointersstrings

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Two PointersRead the beginner guide

Given a string s, return true if it is a palindrome after cleaning it up, and false otherwise.

Understand the problem

What is a palindrome? Text that reads the same forward and backward, like racecar, level or noon.

Here, before checking, you clean the string up:

  1. Ignore case: A and a count as the same letter.
  2. Ignore everything that isn't a letter or a digit: spaces, commas, question marks and so on are skipped.

Then check whether what's left reads the same in both directions.

Example 1

text
Input:  s = "Was it a car or a cat I saw?"
Output: true

After cleaning: wasitacaroracatisaw. Read it backward and you get exactly the same letters.

Example 2

text
Input:  s = "race a car"
Output: false

After cleaning: raceacar. Backward it's racaecar, which is different (look at the 4th letter).

Example 3

text
Input:  s = " "
Output: true

After cleaning there's nothing left. An empty string reads the same both ways, so it counts as a palindrome.

Constraints

  • 0 <= s.length <= 2 * 10^5
  • s contains printable ASCII characters.

Note

Follow-up: can you check it with O(1) extra memory, without building a cleaned-up copy of the string?

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Put one pointer at each end of the string, skip anything that isn't a letter or digit, and compare the two characters while walking the pointers toward the middle.

    The simple approach (and its cost)

    The most direct solution is:

    1. Build a cleaned string: lowercase letters and digits only.
    2. Reverse it.
    3. Compare the two.

    This is correct and perfectly fine as a first answer. Its cost is memory: it builds two new strings as long as the input, which is O(n) extra space. The follow-up asks you to avoid that.

    The key insight

    Reversing a string just to compare it is wasteful. A palindrome check only ever compares the first character with the last, the second with the second-to-last, and so on. You can do that directly with two indices, one moving forward from the start and one moving backward from the end.

    This is the two pointers pattern (see the beginner guide linked at the top): two indices moving toward each other replace building a copy.

    Step by step

    Let's try a real palindrome, s = "No, on!":

    Stepleft onright onWhat happens
    1N!! isn't a letter, move right back
    2Nncompare n vs n (lowercased): same ✅
    3oostep inward, compare o vs o: same ✅
    4, step inward: , is junk, move left
    5left and right met in the middle: stop

    Every pair matched, so the answer is true.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Each character is visited at most once, by one of the two pointers.
    • Memory: O(1). We only keep two index numbers, no matter how long the string is.

    Common mistakes

    • Forgetting left < right in the skipping loops. A string with no letters at all, like ".,", would let a pointer run off the end of the string.
    • Comparing without lowercasing. "Aa" is a palindrome, but A !== a.
    • Only skipping spaces. The rule is "letters and digits only", so commas, ?, ! and so on must be skipped too.

    Going deeper

    Two pointers moving toward each other appear again in 3Sum and Container With Most Water. The trick there is the same: each step safely throws away one end, so you never need a nested loop.

    Reference solution

    js
    // A letter (a-z, A-Z) or a digit (0-9). Everything else is skipped.
    const isAlphanumeric = (char) => /[a-z0-9]/i.test(char)
    
    /**
     * @param {string} s
     * @return {boolean}
     */
    export default function isPalindrome(s) {
      let left = 0 // walks forward from the start
      let right = s.length - 1 // walks backward from the end
      while (left < right) {
        // Skip junk on both sides. `left < right` stops us running off the end.
        while (left < right && !isAlphanumeric(s[left])) left++
        while (left < right && !isAlphanumeric(s[right])) right--
        // Compare in lowercase so "A" matches "a".
        if (s[left].toLowerCase() !== s[right].toLowerCase()) return false
        // This pair matched: step both pointers toward the middle.
        left++
        right--
      }
      // Every pair matched.
      return true
    }
    ts
    // A letter (a-z, A-Z) or a digit (0-9). Everything else is skipped.
    const isAlphanumeric = (char: string) => /[a-z0-9]/i.test(char)
    
    export default function isPalindrome(s: string): boolean {
      let left = 0 // walks forward from the start
      let right = s.length - 1 // walks backward from the end
      while (left < right) {
        // Skip junk on both sides. `left < right` stops us running off the end.
        while (left < right && !isAlphanumeric(s[left])) left++
        while (left < right && !isAlphanumeric(s[right])) right--
        // Compare in lowercase so "A" matches "a".
        if (s[left].toLowerCase() !== s[right].toLowerCase()) return false
        // This pair matched: step both pointers toward the middle.
        left++
        right--
      }
      // Every pair matched.
      return true
    }
    python
    def is_palindrome(s: str) -> bool:
        # left walks forward from the start, right walks backward from the end.
        left, right = 0, len(s) - 1
        while left < right:
            # Skip anything that isn't a letter or digit. `left < right` stops us running off the end.
            while left < right and not s[left].isalnum():
                left += 1
            while left < right and not s[right].isalnum():
                right -= 1
            # Compare in lowercase so "A" matches "a".
            if s[left].lower() != s[right].lower():
                return False
            # This pair matched: step both pointers toward the middle.
            left += 1
            right -= 1
        # Every pair matched.
        return True