This is more than a plain "is this string a palindrome?" check. The problem adds two preprocessing rules: ignore case and ignore non-alphanumeric characters. The string "A man, a plan, a canal: Panama" has spaces, commas, and a colon, but after removing those characters and lowercasing the rest, it becomes "amanaplanacanalpanama", which reads the same forwards and backwards.
The two approaches below differ on one decision: whether to build the cleaned-up string explicitly, or skip the ignored characters while comparing.
1 <= s.length <= 2 * 10^5 → With up to 200,000 characters, the solution needs to run in O(n) time. Both approaches do; they differ in space usage.s consists only of printable ASCII characters → The input can contain letters, digits, spaces, punctuation, and symbols, but no Unicode characters. This means a single byte per character and a fixed test for "alphanumeric".Do exactly what the problem describes: remove everything that isn't a letter or digit, convert the rest to lowercase, and check whether the result is a palindrome.
To check whether a string is a palindrome, compare it against its reverse. If the cleaned string equals its reverse, it is a palindrome.
This approach allocates a cleaned string and a reversed copy, both up to n characters. The next approach removes those allocations by comparing characters directly on the original string from both ends.
Work directly on the original string instead of building a cleaned copy. Place one pointer at the start and one at the end. Move them toward each other, skipping any character that isn't alphanumeric. When both pointers rest on alphanumeric characters, compare them case-insensitively. If they ever differ, the string is not a palindrome. If the pointers cross without a mismatch, it is.
This does the filtering and comparison in a single pass, with no extra string allocated.
A palindrome reads the same from both ends, so the i-th alphanumeric character from the front must equal the i-th from the back. The two pointers enumerate exactly those alphanumeric characters in that paired order: skipping ignored characters means each comparison lines up the next front character with the next back character. The sequence of pairs compared is identical to comparing the cleaned string from Approach 1 against its reverse, so the two approaches accept and reject the same strings.
left to 0 and right to the last index of the string.left < right:left forward while it points to a non-alphanumeric character.right backward while it points to a non-alphanumeric character.left >= right, break (all valid characters have been compared).s[left] and s[right].left forward and right backward.