Valid Palindrome
The problem
Section titled “The problem”You get a string with letters, digits, spaces and punctuation. Ignore everything that is
not a letter or digit, and ignore upper versus lower case. Return true if what is left
reads the same forwards and backwards.
"A man, a plan, a canal: Panama" -> true ("amanaplanacanalpanama")"race a car" -> falseKey insight
Section titled “Key insight”The easy way is to build a cleaned, lower-cased copy and compare it with its reverse. That is O(n) time but also O(n) extra space.
You can skip the copy. A palindrome is equal at mirrored positions, so put one pointer
at each end and compare them. If a pointer sits on a character that doesn’t count, step
it inward and look again. If the two characters differ, return false. If the pointers
meet or cross, every pair matched.
Show solutionHide solution
def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: if not s[left].isalnum(): left += 1 elif not s[right].isalnum(): right -= 1 elif s[left].lower() != s[right].lower(): return False else: left += 1 right -= 1 return Trueexport function isPalindrome(s: string): boolean { const isAlnum = (c: string) => /[a-z0-9]/i.test(c); let left = 0; let right = s.length - 1; while (left < right) { if (!isAlnum(s[left])) left++; else if (!isAlnum(s[right])) right--; else if (s[left].toLowerCase() !== s[right].toLowerCase()) return false; else { left++; right--; } } return true;}class Solution { public boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { if (!Character.isLetterOrDigit(s.charAt(left))) { left++; } else if (!Character.isLetterOrDigit(s.charAt(right))) { right--; } else if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } else { left++; right--; } } return true; }}Complexity
Section titled “Complexity”- Time: O(n) — each pointer moves inward at most n steps in total, and each step is O(1).
- Space: O(1) — only two indices; no cleaned copy is built.
Watch out for
Section titled “Watch out for”- Skip first, compare second. Only compare when both pointers are on valid
characters. Otherwise
"ab_a"or".,"gives wrong answers. - Empty after cleaning is a palindrome.
" "returnstrue, so the loop must handle it without special cases (left < rightalready does). - Digits count.
"0P"isfalse:0andpare different characters. Don’t treat “alphanumeric” as “letters only”.
Variations
Section titled “Variations”Valid Palindrome II (LeetCode 680)
Section titled “Valid Palindrome II (LeetCode 680)”Return true if the string can become a palindrome after deleting at most one
character. The trick: run the same two pointers. At the first mismatch, try
skipping the left character or the right one, and check whether the rest of that
range is a palindrome. Still O(n).
Palindromic Substrings (LeetCode 647)
Section titled “Palindromic Substrings (LeetCode 647)”Count every substring that is a palindrome. The trick: expand outward from each of the 2n-1 possible centers (each character and each gap) while the two ends match. The pointers move apart instead of together. O(n²).
Longest Palindromic Substring (LeetCode 5)
Section titled “Longest Palindromic Substring (LeetCode 5)”Find the longest palindromic substring. The trick: the same expand-around-center idea as above, keeping the best range seen. O(n²) time and O(1) space.