Valid Palindrome
Easy · Two pointers
Jump to codeCheck whether a string reads the same in both directions after ignoring non-alphanumeric characters and letter case. An empty cleaned string counts as a palindrome.
Examples
Example 1
s = "A man, a plan, a canal: Panama"
Output: true
Example 2
s = "race a car"
Output: false
Constraints
- 1 <= s.length <= 1000
- s is made up of only printable ASCII characters.
Need a hint?
You can skip punctuation without building a cleaned copy.
Asked in real interviews
Candidates reported versions of Valid Palindrome from these company interviews. Some company questions are locked and open with Premium or XP.
- Check a Palindrome While Ignoring Case and PunctuationAmazon
- Solve word segmentation and React palindrome validationIntuit
Solution approach
Place pointers at both ends. Advance each past characters that are not letters or digits. Compare normalized characters, failing on a mismatch, then move inward. Stop when the pointers meet or cross.
Complexity
O(n) time and O(1) extra space.
Python reference solution
def isPalindrome(s):
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
elif not s[right].isalnum():
right -= 1
elif s[left].lower() != s[right].lower():
return False
else:
left += 1
right -= 1
return True
JavaScript solution
function isPalindrome(s) {
let left = 0, right = s.length - 1;
const alphanumeric = char => /[a-z0-9]/i.test(char);
while (left < right) {
if (!alphanumeric(s[left])) left++;
else if (!alphanumeric(s[right])) right--;
else if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
else { left++; right--; }
}
return true;
}
Java solution
import java.util.*;
class Solution {
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
char a = s.charAt(left), b = s.charAt(right);
if (!Character.isLetterOrDigit(a)) left++;
else if (!Character.isLetterOrDigit(b)) right--;
else if (Character.toLowerCase(a) != Character.toLowerCase(b)) return false;
else { left++; right--; }
}
return true;
}
}
C++ solution
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool isPalindrome(string s) {
int left = 0, right = (int)s.size() - 1;
while (left < right) {
unsigned char a = s[left], b = s[right];
if (!isalnum(a)) left++;
else if (!isalnum(b)) right--;
else if (tolower(a) != tolower(b)) return false;
else { left++; right--; }
}
return true;
}
};
Trace a boundary case, then implement the approach in the editor. Submit checks your solution against all 8 test cases.
Keep your reasoning, pseudocode, and edge cases here.
Notes stay in this browser when storage is available.
Accepted submissions mark this problem complete. Progress stays in this browser.
[ "A man, a plan, a canal: Panama" ]
true
[ "race a car" ]
false
[ " " ]
true
[ "No lemon, no melon" ]
true
[ "0P" ]
false
Drafts are saved per language in this browser when storage is available.