Valid Palindrome solution explained
Valid Palindrome asks whether a sentence reads the same in both directions once you ignore case and every character that is not a letter or digit. The expected solution uses two indexes, one from each end, that skip ignored characters and compare the rest case-insensitively, which takes O(n) time and O(1) extra space instead of building a cleaned copy.
By Evin JohnPublished 6 min read
Restating the problem
Take a string that may contain spaces, punctuation, digits and letters in either case. Keep only the letters and digits, and treat uppercase and lowercase as the same. If what remains reads identically from left to right and from right to left, answer true. A string that becomes empty after cleaning counts as a palindrome, because there is nothing to disagree.
| Input | After cleaning | Palindrome? |
|---|---|---|
Step on no pets! | steponnopets | Yes |
Was it a cat I saw? | wasitacatisaw | Yes |
Top spot | topspot | Yes |
race a fast car | raceafastcar | No |
8a, a8 | 8aa8 | Yes |
?! | empty | Yes |
Ask what counts as a letter. The usual version means ASCII letters and digits only. Accented letters, other scripts and emoji raise questions about case folding and about what one character even is. The code on this page sticks to ASCII and says so, which is the safest assumption to state out loud.
What a strong answer demonstrates
Interviewers often use this as a two-pointer warm-up. They want to see the skip loops written without index errors, a clear stop condition, and an honest statement of extra space. A candidate who first writes the cleaned-copy version, notes its O(n) memory, and then removes that memory with pointers is showing exactly the habit the question is meant to surface. The one-deletion follow-up then tests whether you can reuse your own helper instead of starting over.
Version one: clean, then reverse
Filter the string down to letters and digits, lowercase it, and compare it with its reversal. It is short and hard to get wrong. Its cost is an extra string as long as the input, and in an interview you should say that before the interviewer has to ask.
def keep(ch):
return ch.isascii() and ch.isalnum()
def mirror_by_copy(text):
cleaned = [ch.lower() for ch in text if keep(ch)]
return cleaned == cleaned[::-1]The isascii() check is there on purpose. Python's isalnum() alone accepts letters from any script, while a JavaScript regex such as a to z plus 0 to 9 does not, so without it the two languages would disagree on input like accented words.
Version two: pointers from both ends
Put lo at the first index and hi at the last. While lo is left of hi, push lo right past anything ignored and push hi left past anything ignored, keeping both inside the bounds. Compare the two characters after lowercasing. A mismatch means false. A match moves both pointers one step inward. When they meet or cross, every pair has matched.
def mirror(text):
lo, hi = 0, len(text) - 1
while lo < hi:
while lo < hi and not keep(text[lo]):
lo += 1
while lo < hi and not keep(text[hi]):
hi -= 1
if text[lo].lower() != text[hi].lower():
return False
lo += 1
hi -= 1
return Truefunction keepChar(ch) {
return /[A-Za-z0-9]/.test(ch);
}
function mirror(text) {
let lo = 0;
let hi = text.length - 1;
while (lo < hi) {
while (lo < hi && !keepChar(text[lo])) lo++;
while (lo < hi && !keepChar(text[hi])) hi--;
if (text[lo].toLowerCase() !== text[hi].toLowerCase()) return false;
lo++;
hi--;
}
return true;
}The lo < hi guard inside each skip loop is what keeps a string made entirely of punctuation from walking off the end. If both pointers land on the same ignored character, the comparison is of a character with itself and passes, which is the right answer.
Follow-up: one character may be removed
A frequent second part asks whether the text can become a palindrome after deleting at most one character. Scan inward as before. At the first mismatch you have two choices: drop the left character or drop the right one. Check each remaining range with a plain inward scan and answer true if either works. You only branch once, so it stays O(n).
def is_mirror_range(s, lo, hi):
while lo < hi:
if s[lo] != s[hi]:
return False
lo += 1
hi -= 1
return True
def mirror_after_one_cut(s):
lo, hi = 0, len(s) - 1
while lo < hi:
if s[lo] != s[hi]:
return is_mirror_range(s, lo + 1, hi) or is_mirror_range(s, lo, hi - 1)
lo += 1
hi -= 1
return TrueCosts
| Approach | Time | Extra space |
|---|---|---|
| Clean, then compare with reverse | O(n) | O(n) |
| Two pointers with skipping | O(n) | O(1) |
| One deletion allowed | O(n) | O(1) |
| Try deleting each character in turn | O(n²) | O(n) |
Inputs to run by hand
- Empty string and a string of only punctuation: both true.
- One letter: true.
- Mixed case that only matches after folding, like
Top spot. - Digits next to letters, like
8a, a8, to confirm digits are kept. - Ignored characters clustered at one end only, which tests the bounds in the skip loops.
- For the follow-up: a mismatch where only deleting the right-hand character works, so both branches get exercised.
Frequent errors
- Skip loops without the
lo < higuard, which can index past the string. - Comparing before lowercasing, so
Tandtfail. - Dropping digits along with punctuation.
- Claiming O(1) space for the cleaned-copy version.
- In the follow-up, trying only one of the two deletions at the first mismatch.
Explaining it to the interviewer
Fictional example
- Candidate
- I could filter to letters and digits, lowercase, and compare with the reverse. That is linear but uses a full copy.
- Candidate
- To avoid the copy, I keep one index at each end. Each index skips anything that is not a letter or digit, then I compare the two characters ignoring case.
- Candidate
- If they differ I return false, otherwise both move inward. Every character is passed at most once by one of the indexes, so it is linear time with constant extra space.
More pointer practice
Two Sum on a Sorted Array uses the same inward pair of indexes, but decides which one to move by comparing a sum with a target. Trapping Rain Water is a harder version where the pointer with the lower wall moves. If you came here from hashing problems, Longest Consecutive Sequence is the set-based contrast. The coding problems hub lists them all.
Natively in your practice routine
Natively is a desktop assistant for Mac and Windows. While you practice, it can read a problem like this from a screenshot and propose an approach, and its transcript of the session lets you check afterward whether you mentioned the space cost and the bounds checks. The AI interview assistant page describes the wider set of features.
Questions people ask
What is the optimal solution for Valid Palindrome?
Two pointers. Start one at each end, skip characters that are not letters or digits, compare the rest without regard to case, and move inward. It takes O(n) time and O(1) extra space.
Is cleaning the string and reversing it wrong?
No, it is correct and easy to read, but it builds a copy, so it uses O(n) extra space. Mention it first, then offer the pointer version if the interviewer asks for constant space.
How do you handle the version where one character may be deleted?
Walk the pointers inward until the first mismatch, then check whether either remaining slice, skipping the left character or skipping the right one, is a palindrome. That is still O(n).
Do digits count in Valid Palindrome?
In the usual version, yes: letters and digits both count and everything else is ignored. Confirm the rule with the interviewer, along with how non-English letters should be treated.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
