Valid Palindrome
Check whether a phrase reads the same both ways, ignoring case and symbols, with one pointer at each end.
01The problem
A phrase is a palindrome if, after lower-casing it and ignoring everything that isn't a letter or digit, it reads the same forwards and backwards. Return whether s is a palindrome.
| Input | Output | Why |
|---|---|---|
"A man, a plan, a canal: Panama" | true | "amanaplanacanalpanama" |
"race a car" | false | "raceacar" |
Constraints: length 1 to 200,000, printable ASCII.
02How to spot it
- "Reads the same backward": compare the string with its mirror.
- "Ignore non-alphanumeric": junk can be skipped on the fly.
- O(1) extra space wanted: no cleaned copy.
So: two pointers from both ends, moving inward.
03Pseudocode
l = 0 ; r = n - 1
while l < r:
skip l forward past non-alphanumerics
skip r backward past non-alphanumerics
if lower(s[l]) != lower(s[r]): return false
l += 1 ; r -= 1
return true- Put one finger at each end.
- Skip anything that isn't a letter or digit.
- Compare letters, ignoring case, and move inward.
04Watch it work
One finger at each end. We only compare letters and digits, ignoring case.
Pseudocode
- l = 0 ; r = n - 1
- while l < r:
- skip l forward past non-alphanumerics
- skip r backward past non-alphanumerics
- if lower(s[l]) != lower(s[r]): return false
- l += 1 ; r -= 1
- return true
Variables
- l
- 0
- r
- 7
05Step-by-step dry run
- 1R0a1c2e3,4c5a6r7lr
One finger at each end. We only compare letters and digits, ignoring case.
l = 0r = 7
- 2R0a1c2e3,4c5a6r7lr
'R' and 'r' lower-case to r: a match. Move both inward.
l = 0r = 7a = rb = r
- 3R0a1c2e3,4c5a6r7lr
'a' and 'a' lower-case to a: a match. Move both inward.
l = 1r = 6a = ab = a
- 4R0a1c2e3,4c5a6r7lr
'c' and 'c' lower-case to c: a match. Move both inward.
l = 2r = 5a = cb = c
- 5R0a1c2e3,4c5a6r7lr
Skip ',': not a letter or digit.
l = 3r = 3
- 6R0a1c2e3,4c5a6r7
The fingers met and every pair matched: it is a palindrome.
l = 3r = 3
06Java solution
public class ValidPalindrome {
static boolean isPalindrome(String s) {
int l = 0, r = s.length() - 1;
while (l < r) {
while (l < r && !Character.isLetterOrDigit(s.charAt(l))) l++;
while (l < r && !Character.isLetterOrDigit(s.charAt(r))) r--;
char a = Character.toLowerCase(s.charAt(l));
char b = Character.toLowerCase(s.charAt(r));
if (a != b) return false; // mismatch: not a palindrome
l++;
r--;
}
return true;
}
public static void main(String[] args) {
System.out.println(isPalindrome("A man, a plan, a canal: Panama"));
System.out.println(isPalindrome("race a car"));
System.out.println(isPalindrome(".,"));
System.out.println(isPalindrome("0P"));
}
}true false true false
Tricky lines, decoded
l < rinside the skip loops stops them running past each other on strings like".,".Character.isLetterOrDigit: digits count too, so"0P"is not a palindrome.
07Why it works
A palindrome's character at distance d from the start must equal the one at distance d from the end. The two pointers check exactly these pairs, skipping characters that don't count. If every pair matches before the pointers meet, the cleaned string equals its reverse.
Invariant: all letter and digit pairs outside [l, r] already match (ignoring case).
08Time and space
- Time: O(n). Each pointer moves at most n steps in total.
- Space: O(1). Building a cleaned, reversed copy would cost O(n) memory.
09Edge cases
| Input | Output | Why it matters |
|---|---|---|
" " | true | nothing left after cleaning |
"a" | true | single character |
".," | true | only symbols |
"0P" | false | digits count |
"Aa" | true | case-insensitive |
10Common mistakes
- Skipping without
l < r. The pointers fly past each other and go out of bounds. Character.isLetter. Digits must be compared, not ignored: useisLetterOrDigit.- Comparing before lower-casing.
'A'and'a'are differentchars.
11Other approaches
| Approach | Time | Space | Use when |
|---|---|---|---|
| Clean + reverse | O(n) | O(n) | Quick to write |
| Two pointers | O(n) | O(1) | Default answer |
| Regex clean | O(n) | O(n) | Scripting, not interviews |
| Recursion | O(n) | O(n) | Stack overflow risk |
12In the interview
- Longest palindromic substring? (LeetCode 5) Expand around each centre, O(n²).
- Unicode text? Use code points (
codePointAt) so emoji and accents aren't split.
13Check your understanding
Quiz · 2 questions
0 of 2 answered
1. Why does the skip loop also check l < r?
2. Is "0P" a palindrome?
14Solve it yourself
Try it on LeetCode #125.