Palindrome Check
EasyGiven a string s, determine if it is a palindrome. A palindrome reads the same forward and backward. Consider only alphanumeric characters and ignore cases.
Examples
| Input | Output |
|---|---|
| s = "A man, a plan, a canal: Panama" | true |
| s = "race a car" | false |
Python Solution
def is_palindrome(s: str) -> bool:
left, right = 0, len(s) - 1
while left < right:
if not s[left].isalnum():
left += 1
continue
if not s[right].isalnum():
right -= 1
continue
if s[left].lower() != s[right].lower():
return False
left += 1
right -= 1
return TrueJavaScript Solution
function isPalindrome(s) {
let left = 0, right = s.length - 1;
while (left < right) {
if (!/\w/.test(s[left])) { left++; continue; }
if (!/\w/.test(s[right])) { right--; continue; }
if (s[left].toLowerCase() !== s[right].toLowerCase()) return false;
left++;
right--;
}
return true;
}Step-by-Step Explanation
- Use two pointers at the start and end of the string.
- Skip non-alphanumeric characters by moving pointers.
- Compare characters (case-insensitive) at both pointers.
- If they differ, return false. Otherwise move inward and continue.
Complexity Analysis
| Time | O(n) |
| Space | O(1) |
Tags
StringTwo Pointers
Related Problems
Related Tools
All Problems
Two SumReverse a StringFizzBuzzBinary SearchReverse Linked ListMerge Two Sorted ArraysValid ParenthesesMaximum Subarray (Kadane's Algorithm)Remove Duplicates from Sorted ArrayNth Fibonacci NumberValid AnagramFirst Unique CharacterClimbing StairsRoman to IntegerBest Time to Buy and Sell StockContains DuplicateMove ZeroesIntersection of Two ArraysLongest Common Prefix