Skip to content

Valid Palindrome

EasyLeetCode #125Time O(n)Space O(1)

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" -> false

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 True
  • 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.
  • 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. " " returns true, so the loop must handle it without special cases (left < right already does).
  • Digits count. "0P" is false: 0 and p are different characters. Don’t treat “alphanumeric” as “letters only”.

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).

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.