The "Valid Palindrome" problem asks us to determine whether a given string is a palindrome. A palindrome is a sequence that reads the same backward as forward. However, this variant of the problem ignores all non-alphanumeric characters and is case-insensitive. For example, "A man, a plan, a canal: Panama" is considered a valid palindrome.
To solve this efficiently without using additional space to store a cleaned version of the string, we apply the two-pointer approach. We use two indices, one starting from the beginning of the string (L
) and the other from the end (R
), moving inward.
At each step, we skip any character that is not alphanumeric by advancing the pointers. If both characters are alphanumeric, we compare their lowercase versions. If at any point the characters differ, the string is not a palindrome, and we return false.
L = 0
and R = s.length - 1
.L < R
:
s[L]
is not alphanumeric, increment L
.s[R]
is not alphanumeric, decrement R
.lowercase(s[L])
and lowercase(s[R])
. If they differ, return false.L
and decrement R
.This method is efficient because it avoids the overhead of creating a new filtered string. By using the two-pointer approach, we ensure that we check character pairs directly within the original string. Lowercasing both characters standardizes comparison and skipping non-alphanumeric characters ensures compliance with the problem’s constraints.
The solution runs in O(n) time, where n is the length of the input string, since each character is visited at most once. The space complexity is O(1), as we only use a constant number of pointers and comparisons, making this approach optimal for large strings.