Dry run
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.
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
"amanaplanacanalpanama" is a palindrome
"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
Build a cleaned copy of the string (lowercase, letters and digits only) and check whether it equals its own reverse.
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.
Complexity
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.