</>

125. Valid Palindrome

Easy NeetCode 150
Two Pointers Time O(N) Space O(1)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
Two Pointers
Time
O(N)
Space
O(1)

Standard Solution (C++)

SummaryGiven a string, determine whether it reads the same forwards and backwards after discarding all non-alphanumeric characters and treating uppercase and lowercase letters as equivalent.

Approach
  • Use two pointers starting at each end of the string, advancing inward while skipping non-alphanumeric characters.
  • At each step, compare the lowercased characters at the two pointers; if they ever differ, return false.
  • If the pointers meet or cross without a mismatch, the string is a valid palindrome.
  • The standard library's std::isalnum and std::tolower keep the logic concise and correct for all ASCII inputs.
#include <string>
#include <cctype>
using namespace std;

class Solution {
public:
    bool isPalindrome(string s) {
        int l = 0, r = static_cast<int>(s.size()) - 1;

        while (l < r) {
            // Advance past non-alphanumeric characters from each side.
            while (l < r && !isalnum(s[l])) ++l;
            while (l < r && !isalnum(s[r])) --r;

            // Compare case-insensitively.
            if (tolower(s[l]) != tolower(s[r])) return false;

            ++l;
            --r;
        }

        return true;
    }
};
Time O(n) Space O(1)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    bool isAlphaNum(const char &c){
        if((c<='z' && c>='a')||(c<='Z' && c>='A')||(c<='9' && c>='0')){
            return true;
        }
        return false;
    }
    char toLowercase(const char &c){
        if(c<='Z' && c>='A'){
            return c-'A'+'a';
        }
        return c;
    }

    bool isPalindrome(string s) {
        int l=0, r=s.length();

        while(l<r){
            while(l<r && !isAlphaNum(s[l])){
                ++l;
            }
            while(l<r && !isAlphaNum(s[r])){
                --r;
            }

            if(toLowercase(s[l])!=toLowercase(s[r])){
                return false;
            }
            ++l;
            --r;
        }
        return true;
    }
};

// Time Complexity: O(N)
// Space Complexity: O(1)
Time O(N) Space O(1)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern