Valid Palindrome
Easy
Topics
A phrase is a palindrome if, after converting uppercase to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward. Given a string s, return true if it is a palindrome.
Example 1
ignored — not alphanumericcompared
Punctuation and spaces are skipped and case is ignored, so only the shaded characters are compared.
Cells are the characters of the string; the small numbers underneath are indices.
Input: s = "A man, a plan, a canal: Panama" Output: true
Example 2
ignored — not alphanumericmismatch
Reading the compared characters inward from both ends, the shaded pair disagrees, so the answer is
false.Input: s = "race a car" Output: false
Constraints
- 1 <= s.length <= 2*10^5
- s consists of printable ASCII characters.
Editorial — intuition, approach, complexity and pitfalls
Intuition
After lowercasing and stripping non-alphanumeric characters, a palindrome reads identically forwards and backwards. Two pointers converging from both ends confirm this without building a reversed copy (O(1) space).
Approach
- Filter to lowercase alphanumeric characters (or skip non-alphanumerics with two pointers in place).
- Compare the cleaned sequence to its reverse.
- Equal means palindrome.
Walkthrough
s = "A man, a plan, a canal: Panama"
cleaned = "amanaplanacanalpanama"
reads same both ways -> trueComplexity
- Time — O(n): one pass to clean, one comparison.
- Space — O(1): the two-pointer variant compares in place (the shown version uses O(n) for the cleaned list).
Common Pitfalls
- Normalise case as well as stripping non-alphanumerics. Comparing without lowercasing makes
A man, a plan, a canal: Panamareport false, becauseAandaare different characters. - Skip non-alphanumerics on both pointers before comparing. Advancing only one side drifts the two out of alignment on any string with punctuation.
Full Solution — all languages
class Solution:
def isPalindrome(self, s):
f = [c.lower() for c in s if c.isalnum()]
return f == f[::-1]import java.util.*;
class Solution {
public boolean isPalindrome(String s) {
int lo = 0, hi = s.length() - 1;
while (lo < hi) {
while (lo < hi && !Character.isLetterOrDigit(s.charAt(lo))) lo++;
while (lo < hi && !Character.isLetterOrDigit(s.charAt(hi))) hi--;
if (Character.toLowerCase(s.charAt(lo)) != Character.toLowerCase(s.charAt(hi))) return false;
lo++;
hi--;
}
return true;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isPalindrome(string s) {
int lo = 0, hi = (int)s.size() - 1;
while (lo < hi) {
while (lo < hi && !isalnum((unsigned char)s[lo])) lo++;
while (lo < hi && !isalnum((unsigned char)s[hi])) hi--;
if (tolower((unsigned char)s[lo]) != tolower((unsigned char)s[hi])) return false;
lo++;
hi--;
}
return true;
}
};/**
* @param {string} s
* @return {boolean}
*/ var isPalindrome = function(s) {
const f = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return f === f.split('').reverse().join('');
};