We use two pointers, one starting at the beginning (l) and one at the end (r). We move them towards the center, skipping non-alphanumeric characters and comparing values.
- Initialize
l = 0,r = len(s) - 1. - While
l < r:- While
l < rands[l]is not alphanumeric, incrementl. - While
l < rands[r]is not alphanumeric, decrementr. - If
s[l].lower() != s[r].lower(), return False. - Increment
l, decrementr.
- While
- Return True if the loop completes.
- Time Complexity: O(N).
- Space Complexity: O(1).
def is_palindrome(s):
l, r = 0, len(s) - 1
while l < r:
while l < r and not s[l].isalnum():
l += 1
while l < r and not s[r].isalnum():
r -= 1
if s[l].lower() != s[r].lower():
return False
l += 1
r -= 1
return True