Algo-Sim › Two Pointers

Valid Palindrome

Easy · Two Pointers · step through it in Java, Python and C++ on your own input

Ignoring case and every character that is not a letter or digit, does the string read the same both ways?

Problem

A string counts as a palindrome here if, after lowercasing it and dropping every character that is not a letter or a digit, it reads the same left to right and right to left. Given s, return whether it is such a palindrome.

Constraints

Edge cases to test

Follow-up questions

Why not build a cleaned, reversed copy?
That works in O(n) time but O(n) space. Two pointers that skip non-alphanumerics use O(1) space.
What if one character may be deleted?
At the first mismatch, try skipping either side once and check the rest (LC 680): O(n).

Solution

Java

public boolean isPalindrome(String s) {
    int left = 0, right = s.length() - 1;
    while (left < right) {
        if (!Character.isLetterOrDigit(s.charAt(left))) {
            left++;
        } else if (!Character.isLetterOrDigit(s.charAt(right))) {
            right--;
        } else {
            char a = Character.toLowerCase(s.charAt(left));
            char b = Character.toLowerCase(s.charAt(right));
            if (a != b) return false;
            left++;
            right--;
        }
    }
    return true;
}

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
        else:
            a, b = s[left].lower(), s[right].lower()
            if a != b:
                return False
            left += 1
            right -= 1
    return True

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    bool isPalindrome(string &s) {
        int left = 0, right = int(s.size()) - 1;
        while (left < right) {
            if (!isalnum(s[left])) {
                left++;
            } else if (!isalnum(s[right])) {
                right--;
            } else {
                char a = tolower(s[left]);
                char b = tolower(s[right]);
                if (a != b)
                    return false;
                left++;
                right--;
            }
        }
        return true;
    }
};

More Two Pointers problems