mediumStack
Alphanumeric Palindrome Validation Solution
Problem Statement
You are given a string `s`. Determine if it is a palindrome, considering only alphanumeric characters and ignoring case sensitivity.
Examples
Example 1:
Input:s = "A man, a plan, a canal: Panama"
Output:true
Explanation: The string is a palindrome when ignoring non-alphanumeric characters and case.
Example 2:
Input:s = "Not a palindrome"
Output:false
Example 3:
Input:s = "Was it a car or a cat I saw?"
Output:true
Time: O(n) Space: O(n)
The optimal approach involves using two pointers, one at the start and one at the end of the string, and moving them towards each other while comparing characters and skipping non-alphanumeric characters. This approach has a time complexity of O(n) where n is the length of the string.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def is_palindrome(s):
s = ''.join(e for e in s if e.isalnum()).lower()
left, right = 0, len(s) - 1
while left < right:
if s[left] != s[right]:
return False
left, right = left + 1, right - 1
return True