Try it first — give it 15 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get a string s. Pretend you first lowercase every letter and throw away every character that isn't a letter or a digit (spaces, commas, colons, quotes, underscores). Is what's left a palindrome, meaning it reads the same from both directions? Return true or false.
Constraints that matter: s can be up to 2·10⁵ characters of printable ASCII. A string with no letters or digits at all counts as an empty string, and an empty string is a palindrome.
Example: "A man, a plan, a canal: Panama" becomes "amanaplanacanalpanama", which is a palindrome, so the answer is true. "race a car" becomes "raceacar", which is not.
Start with brute force
The direct way: build the cleaned string (lowercase, letters and digits only), reverse it, and compare.
clean = [c.lower() for c in s if c.isalnum()]
return clean == clean[::-1]This is correct and already O(n) time. Its only cost is O(n) extra memory: you store a cleaned copy and then a reversed copy. Interviewers often accept it as a first answer and then ask, "can you do it without the extra copies?" That's the real question.
Building the intuition
What does "reads the same backwards" actually say? Write out a palindrome and draw lines between matching characters:
r a c e c a r
| | | ^ | | |
first matches last, second matches second-to-last, ...So checking a palindrome is just comparing pairs from the outside in. The reversed copy was only a roundabout way to line those pairs up.
You can line them up yourself with two indices: left starting at the front and right at the back. Compare, then move both one step inwards. When they meet, every pair has been checked.
Now add the messy part, the characters you're supposed to ignore. You don't need to delete them. When left is sitting on a comma, just step it forward. When right is on a space, step it back. Each pointer skips the junk on its own side before you compare.
That's the core of the opposite-end pointers family you'll use all through this stage. Each comparison settles both ends for good, so the search space shrinks from both sides.
The optimal approach
- Set
left = 0andright = len(s) - 1. - While
left < right:- move
leftforward while it's on a non-alphanumeric character (and stillleft < right); - move
rightbackward the same way; - if
s[left]ands[right]differ after lowercasing, returnfalse; - otherwise move both inwards:
left += 1,right -= 1.
- move
- If the loop ends, every pair matched. Return
true.
The subtle detail: the inner skipping loops also check left < right. Without it, a string like ".," or " " lets left run off the end of the string looking for a letter that isn't there. With the guard, the pointers just meet and the answer is true, which is correct: an empty cleaned string is a palindrome.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def isPalindrome(self, s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
# Skip anything that isn't a letter or digit: it doesn't count
while left < right and not s[left].isalnum():
left += 1
while left < right and not s[right].isalnum():
right -= 1
# Compare case-insensitively: 'A' and 'a' are the same letter
if s[left].lower() != s[right].lower():
return False
# This pair matched, so both ends move inwards
left += 1
right -= 1
return True # the pointers met without a mismatchclass Solution {
public:
bool isPalindrome(string s) {
int left = 0, right = (int)s.size() - 1;
while (left < right) {
// Skip anything that isn't a letter or digit: it doesn't count
while (left < right && !isalnum((unsigned char)s[left])) left++;
while (left < right && !isalnum((unsigned char)s[right])) right--;
// Compare case-insensitively: 'A' and 'a' are the same letter
if (tolower((unsigned char)s[left]) != tolower((unsigned char)s[right])) {
return false;
}
// This pair matched, so both ends move inwards
left++;
right--;
}
return true; // the pointers met without a mismatch
}
};class Solution {
public boolean isPalindrome(String s) {
int left = 0, right = s.length() - 1;
while (left < right) {
// Skip anything that isn't a letter or digit: it doesn't count
while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
// Compare case-insensitively: 'A' and 'a' are the same letter
if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
return false;
}
// This pair matched, so both ends move inwards
left++;
right--;
}
return true; // the pointers met without a mismatch
}
}/**
* @param {string} s
* @return {boolean}
*/
var isPalindrome = function (s) {
const isAlnum = (c) => /[a-zA-Z0-9]/.test(c);
let left = 0, right = s.length - 1;
while (left < right) {
// Skip anything that isn't a letter or digit: it doesn't count
while (left < right && !isAlnum(s[left])) left++;
while (left < right && !isAlnum(s[right])) right--;
// Compare case-insensitively: 'A' and 'a' are the same letter
if (s[left].toLowerCase() !== s[right].toLowerCase()) {
return false;
}
// This pair matched, so both ends move inwards
left++;
right--;
}
return true; // the pointers met without a mismatch
};Dry run
s = "race a car". The indices are r0 a1 c2 e3 _4 a5 _6 c7 a8 r9, where _ stands for a space.
| left | right | After skipping | Compare | Result |
|---|---|---|---|---|
| 0 | 9 | 0, 9 | r vs r | match, move in |
| 1 | 8 | 1, 8 | a vs a | match, move in |
| 2 | 7 | 2, 7 | c vs c | match, move in |
| 3 | 6 | right skips the space at 6, so 3, 5 | e vs a | mismatch → false |
Three pairs matched, and the fourth didn't. We never built a cleaned copy.
Complexity
- Time: O(n).
leftonly moves right andrightonly moves left, and they stop when they meet. Together they take at most n steps, skips included. - Space: O(1). Two integers. No copies of the string.
Edge cases and traps
- Digits count.
"0P"isfalse:0andpare both kept and they differ. Useisalnum, notisalpha. - Only punctuation or spaces.
" "or".,"istrue. Keep theleft < rightguard inside the skipping loops. - Case. Compare
lower(s[left])withlower(s[right]).'A'and'a'must match. - Underscores and quotes are junk.
"ab_a"istrue, because_is neither a letter nor a digit. - C++
isalnumonchar. Cast tounsigned charfirst. Passing a negativechartoisalnumis undefined behaviour.
Say it in the interview
"A palindrome means the first character matches the last, the second matches the second-to-last, and so on. So I'll use two pointers, one at each end. Each pointer skips anything that isn't a letter or digit, then I compare the two characters in lowercase and return false on the first mismatch. If the pointers meet, it's a palindrome. That's O(n) time and O(1) space, because I never build a cleaned copy of the string."
Follow-ups interviewers ask
- "What if you may delete at most one character?" That's Valid Palindrome II. On the first mismatch, try skipping either the left character or the right one, and check whether the rest is a palindrome. Still O(n).
- "Find the longest palindromic substring instead." You need a different idea, expanding outwards from every centre. You'll meet it as Longest Palindromic Substring in the Dynamic Programming stage.
- "What about Unicode?" Then "letter" and "lowercase" depend on the language. You'd use the language's Unicode-aware character functions, and possibly normalise accents first.
Practise the same idea
This is Day 19 of a free 90-day plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free