The signal
Compare a sequence against its own reverse → two pointers from opposite ends. The palindrome check is the pattern in its purest form: no arithmetic, no sorting, just “do these two ends agree, and move inward.”
The filtering requirement is what makes this an interview question rather than a one-liner.
Approach ladder
1. Clean, then reverse and compare — O(n) space
Strip non-alphanumerics, lowercase it, then compare against the reversed copy. Two lines, correct, and it allocates two extra strings. Perfectly reasonable to state first.
2. What is it wasting?
The whole cleaned copy. You never need the filtered string as an object — you only ever need the next valid character from each end, one at a time.
3. Optimal — two pointers with skipping, O(1) space
bool isPalindrome(string s) {
int l = 0, r = s.size() - 1;
while (l < r) {
while (l < r && !isalnum(s[l])) l++;
while (l < r && !isalnum(s[r])) r--;
if (tolower(s[l]) != tolower(s[r])) return false;
l++; r--;
}
return true;
}
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;
}
Walkthrough
"A man, a plan" — abbreviated:
| l | r | s[l] | s[r] | action |
|---|---|---|---|---|
| 0 | 11 | A | n | compare a vs n → mismatch… |
(That example isn’t a palindrome; the full "A man, a plan, a canal: Panama" is. Trace the real one
by hand — the skipping is where mistakes hide.)
Complexity
- Time O(n) — each pointer moves inward only, so together they cover the string once.
- Space O(1) — two indices.
Traps
- Missing
l < rinside the skip loops.",,,,"walksloff the end and you read out of bounds (C++) or getundefined(JS). - Forgetting digits. “Alphanumeric” includes
0-9; a letters-only test fails on"0P". - Case. Lowercase both sides before comparing, every time.
- Using
isalnumon a negativecharin C++. Technically UB for non-ASCII input; cast tounsigned charif the constraints allow extended characters.
Blank re-solve prompt
Check whether a string is a palindrome, ignoring case and non-alphanumeric characters, in O(1) extra space. Make sure
",.;"and""both return true.