Approach
- Normalize the string:
- convert to lowercase
- remove non-alphanumeric characters
- Initialize two pointers:
lat the startrat the end
- Compare mirrored characters while
l < r:- if they differ, return
false - if they match, move inward (
l++,r--)
- if they differ, return
- If the loop completes, return
true.
Implementation
export function isPalindrome(s: string): boolean {
const normalized = s.toLowerCase().replace(/[^a-z0-9]/g, "");
if (normalized.length <= 1) return true;
let l = 0;
let r = normalized.length - 1;
while (l < r) {
if (normalized[l] !== normalized[r]) {
return false;
}
l++;
r--;
}
return true;
}Complexity
- Time O(n): We scan each character once while normalizing and at most once more while comparing mirrored pairs.
- Space O(n): The normalized string may store up to all characters from the input.