Valid Palindrome (LeetCode 125): Solution and Explanation
Given a string, decide whether it reads the same forward and backward once you ignore case and drop every character that is not a letter or digit. An empty cleaned string counts as a palindrome.
Watch it run step by step
Try your own input and write the code →Intuition
The most literal solution cleans the string first: keep only letters and digits, lowercase them, then compare the result with its reverse. That is two short lines in Python and runs in O(n) time, but it builds a new string (and a reversed copy) the size of the input. It is a fine answer, yet interviewers usually follow up by asking for constant extra space.
A palindrome check is really a sequence of comparisons between mirror positions: the first character against the last, the second against the second to last, and so on. Two pointers express that directly. Put l at the start and r at the end, compare, and move both inward. The only twist is the junk characters. Instead of removing them up front, let each pointer skip over them on the fly until it lands on a letter or digit, then compare those two characters case-insensitively.
If any pair differs, you can stop immediately with false. If the pointers meet or cross without a mismatch, every mirror pair matched and the answer is true. Each character is visited by at most one pointer, so this is still linear time, and it uses only two integer indices. The reference code also writes its own alphaNum check using character code ranges, which is what an interviewer may ask for if built-in helpers like isalnum are off limits.
One detail worth noticing is that the skip loops and the outer loop all share the condition that the pointers have not crossed. That single guard is what makes strings of pure punctuation, single characters, and empty strings all fall through to true without special cases.
Approach: Two pointers with skipping
- Initialize
l = 0andr = len(s) - 1. - While
l < r, advancelpast any character for whichalphaNumis false, keepingl < r. - Likewise move
rleft past non-alphanumeric characters whiler > l. - Compare
s[l].lower()withs[r].lower(). If they differ, returnFalse. - Move both pointers inward with
l, r = l + 1, r - 1and repeat. - When the loop ends without a mismatch, return
True.
Step-by-step example
s = "ab, A"
- Start with l = 0 ('a') and r = 4 ('A'). Both are alphanumeric, and 'a' equals 'a' after lowercasing. Move to l = 1, r = 3.
- s[1] = 'b' is alphanumeric. s[3] = ' ' is not, so r moves to 2, which is ',' and also not alphanumeric, so r moves to 1. Now r equals l and the skip loop stops.
- Compare s[1] with s[1]: 'b' equals 'b'. Move to l = 2, r = 0.
- Now l is not less than r, so the loop ends and the function returns True. The cleaned string "aba" is indeed a palindrome.
Code: Python, Java, C++
1class Solution:
2 def isPalindrome(self, s: str) -> bool:
3 l, r = 0, len(s) - 1
4
5 while l < r:
6 while l < r and not self.alphaNum(s[l]):
7 l += 1
8 while r > l and not self.alphaNum(s[r]):
9 r -= 1
10
11 if s[l].lower() != s[r].lower():
12 return False
13
14 l, r = l + 1, r - 1
15
16 return True
17
18 def alphaNum(self, c):
19 return (ord('A') <= ord(c) <= ord('Z') or
20 ord('a') <= ord(c) <= ord('z') or
21 ord('0') <= ord(c) <= ord('9'))1class Solution {
2 public boolean isPalindrome(String s) {
3 int l = 0;
4 int r = s.length() - 1;
5
6 while (l < r) {
7 while (l < r && !Character.isLetterOrDigit(s.charAt(l))) {
8 l++;
9 }
10 while (l < r && !Character.isLetterOrDigit(s.charAt(r))) {
11 r--;
12 }
13
14 if (Character.toLowerCase(s.charAt(l)) != Character.toLowerCase(s.charAt(r))) {
15 return false;
16 }
17 l++;
18 r--;
19 }
20 return true;
21 }
22}1class Solution {
2public:
3 bool isPalindrome(string s) {
4 int l = 0;
5 int r = s.length() - 1;
6
7 while (l < r) {
8 while (l < r && !isalnum(s[l])) {
9 l++;
10 }
11 while (l < r && !isalnum(s[r])) {
12 r--;
13 }
14
15 if (tolower(s[l]) != tolower(s[r])) {
16 return false;
17 }
18 l++;
19 r--;
20 }
21 return true;
22 }
23};Time and space complexity
O(n)
Every index is passed over by either the left pointer or the right pointer at most once, and each step does constant work.
O(1)
Only the two indices are stored. No cleaned or reversed copy of the string is created.
Other approaches
Clean and reverse (time O(n), space O(n))
Build a new string of lowercase alphanumeric characters and compare it with its reverse. It is the clearest one-liner and fine when memory is not a concern.
Recursive mirror check (time O(n), space O(n))
Compare the outer characters and recurse on the inside, skipping junk. It shows the same idea recursively but uses O(n) stack depth and can overflow on long inputs.
Common mistakes
- Omitting the
l < rguard in the inner skip loops. A string made entirely of punctuation, such as ".,", would push a pointer out of bounds. - Forgetting that digits count. "0P" is not a palindrome, and code that only keeps letters would wrongly treat it as "p".
- Comparing without lowercasing, so "Aa" fails even though it should pass.
- Moving only one pointer after a successful comparison. Both must step inward, otherwise the same character is compared repeatedly.
Frequently asked questions
How do you check a palindrome ignoring non-alphanumeric characters?
Use two pointers from both ends. Skip characters that are not letters or digits, compare the remaining characters case-insensitively, and move inward until the pointers meet.
Is an empty string a valid palindrome?
Yes. A string with no alphanumeric characters cleans to an empty string, which reads the same in both directions, so the function returns true.
Can you solve Valid Palindrome in O(1) space?
Yes. The two pointer approach compares characters in place and stores only two indices, unlike the clean and reverse method that allocates new strings.
Why write a custom alphaNum function?
Interviewers sometimes ask you to avoid built-ins like isalnum. Checking whether the character code falls in the ranges for A to Z, a to z, or 0 to 9 does the same job explicitly.