Determine if string is a palindrome, ignoring non-alphanumeric characters and case.
"A man, a plan, a canal: Panama" → true
# 🔁 Two Pointers Example
#
# Problem: Valid Palindrome
# Given a string, determine if it is a palindrome, ignoring non-alphanumeric characters and case.
#
# Input Examples:
# valid_palindrome("A man, a plan, a canal: Panama") => true
# valid_palindrome("race a car") => false
#
# Time Complexity: O(n), where n is the length of the string.
def valid_palindrome(s)
left, right = 0, s.length - 1
while left < right
# Skip non-alphanumeric characters on the left
left += 1 until left >= right || s[left].match?(/[a-zA-Z0-9]/)
# Skip non-alphanumeric characters on the right
right -= 1 until left >= right || s[right].match?(/[a-zA-Z0-9]/)
# Compare lowercase versions of characters
return false if s[left].downcase != s[right].downcase
left += 1
right -= 1
end
true
O(n)
O(1)