Valid Palindrome
Easy
StringTwo Pointers
Problem
Given a string, return true if it reads the same forwards and backwards once you ignore non-alphanumeric characters and case.
Example 1
Input: s = "A man, a plan, a canal: Panama"
Output: true
Example 2
Input: s = "race a car"
Output: false
Example 3
Input: s = " "
Output: true
Constraints
- 1 ≤ s.length ≤ 2·10⁵
- s may contain any printable ASCII
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def isPalindrome(self, s):
t = [c.lower() for c in s if c.isalnum()]
return t == t[::-1]
Java
class Solution {
public boolean isPalindrome(String s) {
int left = 0;
int right = s.length() - 1;
while (left < right) {
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) {
left++;
}
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) {
right--;
}
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
left++;
right--;
}
return true;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Valid Palindrome interactively → ← All solutions