12. Valid Palindrome
easyAsked at SquarespaceDecide whether a string is a palindrome after stripping non-alphanumeric characters and lowercasing; Squarespace uses it to gauge two-pointer fluency on cleaned input.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given a string s, return true if it is a palindrome after converting it to lowercase and removing all non-alphanumeric characters. An empty string counts as a palindrome.
Constraints
1 <= s.length <= 2 * 10^5s consists only of printable ASCII characters
Examples
Example 1
s="A man, a plan, a canal: Panama"trueExample 2
s="race a car"falseApproaches
1. Clean and reverse
Build a cleaned lowercase string then compare it to its reverse.
- Time
- O(n)
- Space
- O(n)
const clean = s.toLowerCase().replace(/[^a-z0-9]/g, '');
return clean === clean.split('').reverse().join('');Tradeoff:
2. Two pointers, skip non-alnum
Walk left and right inward, skipping non-alphanumerics and comparing lowercase chars. Constant extra memory.
- Time
- O(n)
- Space
- O(1)
function isPalindrome(s) {
const ok = c => /[a-z0-9]/i.test(c);
let l = 0, r = s.length - 1;
while (l < r) {
while (l < r && !ok(s[l])) l++;
while (l < r && !ok(s[r])) r--;
if (s[l].toLowerCase() !== s[r].toLowerCase()) return false;
l++; r--;
}
return true;
}Tradeoff:
Squarespace-specific tips
Squarespace evaluators want you to handle empty strings up front and to note that the same cleaning logic shows up when canonicalizing user-typed URL slugs at publish time.
Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Practice these live with InterviewChamp.AI
Drill Valid Palindrome and other Squarespace interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →