Valid Palindrome
Valid Palindrome is LeetCode 125 (Easy). Given a string s of printable ASCII characters, return true if it reads the same forwards and backwards once you:
- remove all non-alphanumeric characters, keeping only letters and digits, and
- treat uppercase and lowercase letters as the same.
A string with no letters or digits at all counts as a palindrome. s can be 200,000 characters long, so one linear pass is the target.
- 1 <= s.length <= 2 * 10⁵
- s consists only of printable ASCII characters.
Intuition
In a palindrome the first character matches the last, the second matches the second-to-last, and so on inward. So check it from the outside in: one pointer at each end, moving toward each other, comparing as they go.
- Characters that do not count: when a pointer sits on a space or punctuation mark, move that pointer alone past it. The two sides can hold different amounts of punctuation, so the pointers do not move in step.
- Characters that count: compare them in lowercase. One mismatch proves the string is not a palindrome.
If the pointers meet with no mismatch, every pair matched. This check builds no cleaned copy, so it needs only O(1) extra space.
"Does it read the same from both ends" is a two-pointer walk inward. Extra rules about which characters count become a skip step for each pointer, not a preprocessing pass.
Approach
Before reading on, decide what each pointer should do when it lands on a comma, and how you stop a pointer from running past the other while it skips. Aim for O(n) time and O(1) extra space.
Two ways to solve it
Walk inward from both ends, skipping characters that do not count and comparing the rest in lowercase.
- No copy: O(1) extra space.
- Early exit: stops at the first mismatch.
The answer interviewers expect.
Keep only the letters and digits, lowercase them, and compare the result with its reverse.
- Shortest code: two lines.
- Cost: builds a copy, and its reverse, of up to 200,000 characters.
The obvious first idea.
Both read each character once. The two pointers skip the copy, so they need O(1) space and can stop early. The steps, code and live demo follow the two pointers, and the cleaned-string code comes after the demo.
Place a pointer at each end
Set left = 0 and right = len(s) - 1. Every character outside the two pointers has already been dealt with, so the loop only runs while left < right.
Skip one character that does not count
If s[left] is not a letter or digit, move left one step right and go round again; otherwise, if s[right] is not, move right one step left. Moving one pointer per round means left < right is checked again before the next comparison, so a pointer can never skip past the other.
Compare the two characters in lowercase
When both pointers sit on letters or digits, compare s[left].lower() with s[right].lower(). If they differ, return false at once: in any palindrome these two positions must hold the same character.
Step both pointers inward
On a match, move both pointers one step in. When they meet or cross, every pair has matched and the answer is true. The middle character of an odd-length string mirrors itself, so it is never compared.
Code in Python, C++ and Java
Clean the string, then reverse it
Build a new string from the letters and digits only, in lowercase. The original is a valid palindrome exactly when that cleaned string equals its own reverse.
Common pitfalls
Skipping in an inner loop with no bounds check
while not s[left].isalnum():
left += 1while left < right and not s[left].isalnum():
left += 1On ".," the inner loop moves left past both characters and then reads s[2], which does not exist, so the code crashes. Any string made only of punctuation and spaces triggers it, and the right answer for such a string is true.
Keeping letters but dropping digits
if not s[left].isalpha():
if not s[left].isalnum():
Digits count too. On "0P" the wrong check skips the 0, leaves only P, and returns true. The real comparison is 0 against p, so the answer is false.
Comparing before lowercasing
elif s[left] != s[right]:
elif s[left].lower() != s[right].lower():
Case is ignored, so "Aa" must return true. The raw comparison sees A and a as different characters and returns false.
Edge cases
For " " or "?!", the pointers skip until they meet without making a single comparison, and the answer is true: the empty string reads the same both ways.
left and right start equal, the loop never runs, and the answer is true.
Complexity
Valid Palindrome FAQ
Does Python's isalnum match the problem's idea of alphanumeric?
For this problem, yes, because the input is printable ASCII. On other text, str.isalnum() also accepts letters such as é and symbols such as ², and Java's Character.isLetterOrDigit accepts é too. If the input could hold non-ASCII text, test the ranges a-z, A-Z and 0-9 directly.