DSA Visualizer · 25 visualizationsValid Palindrome
EasyTwo Pointers

Valid Palindrome

A phrase is a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward. Given a string s, return true if it is a palindrome.

s = "A,b,a"Step 1 of 5
A
0l
,
1
b
2
,
3
a
4r

Start with l at the first character and r at the last. Only letters and digits count, and uppercase and lowercase are treated as equal.

Pythontime O(n) · space O(1)
1def isPalindrome(s):
2 l, r = 0, len(s) - 1
3 while l < r:
4 while l < r and not s[l].isalnum():
5 l += 1
6 while l < r and not s[r].isalnum():
7 r -= 1
8 if s[l].lower() != s[r].lower():
9 return False
10 l, r = l + 1, r - 1
11 return True
Variables
l0
r4
s[l]A
s[r]a

Problem

A phrase is a palindrome if, after converting all uppercase letters to lowercase and removing all non-alphanumeric characters, it reads the same forward and backward. Given a string s, return true if it is a palindrome.

Examples

Input: s = "A man, a plan, a canal: Panama"Output: true

"amanaplanacanalpanama" is a palindrome

Input: s = "race a car"Output: false

"raceacar" reads differently in reverse

Constraints

  • 1 ≤ s.length ≤ 2 × 10⁵
  • s consists of printable ASCII characters

Intuition

Two pointers start at the two ends and walk toward the middle. Non-alphanumeric characters are skipped, and the remaining characters are compared ignoring case. If every compared pair matches, the string is a palindrome.

Brute force → Optimal

Brute force

Build a cleaned copy of the string (lowercase, letters and digits only) and check whether it equals its own reverse.

Time O(n)Space O(n)
Optimal

Two pointers from both ends. Skip non-alphanumeric characters on each side, compare the lowercased characters, then step both pointers inward. No extra string is built.

Time O(n)Space O(1)

Complexity

Time O(n)Space O(1)

Edge cases

  • A string of only non-alphanumeric characters, such as `".,"`: it cleans down to nothing and is a palindrome.
  • A single character or an empty cleaned string: the pointers meet immediately, so the answer is `true`.

Common mistakes

  • Comparing characters without lowercasing, so `"Aa"` is wrongly reported as not a palindrome.
  • Forgetting the `l < r` guard inside the skip loops, which lets a pointer run past the other and read outside the string.
Next up3Sum
Two Sum is free. Enroll to unlock every visualization and save where you stopped.Enroll free