Valid Palindrome
Problem Statement
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. A palindrome reads the same forward and backward. This is an easy-level problem solved using the two-pointer technique.
Example
Input: s = "A man, a plan, a canal: Panama"
Output: true (ignoring non-alphanumeric characters and case, it reads "amanaplanacanalpanama")
Input: s = "race a car"
Output: false
Code
Java
Python
JavaScript
public class Solution { public boolean isPalindrome(String s) { int left = 0, right = s.length() - 1; while (left < right) { while (left < right && !Character.isLetterOrDigit(s.charAt(left))) { left++; } while (left < right && !Character.isLetterOrDigit(s.charAt(right))) { right--; } if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) { return false; } left++; right--; } return true; } }
def is_palindrome(s): left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True # Example usage print(is_palindrome("A man, a plan, a canal: Panama")) # True print(is_palindrome("race a car")) # False
function isPalindrome(s) { let left = 0, right = s.length - 1; while (left < right) { while (left < right && !/[a-zA-Z0-9]/.test(s[left])) { left++; } while (left < right && !/[a-zA-Z0-9]/.test(s[right])) { right--; } if (s[left].toLowerCase() !== s[right].toLowerCase()) { return false; } left++; right--; } return true; } // Example usage console.log(isPalindrome("A man, a plan, a canal: Panama")); // true console.log(isPalindrome("race a car")); // false
Explanation
- Use two pointers: one starting from the left, one from the right.
- Skip non-alphanumeric characters by incrementing or decrementing pointers.
- Compare the characters (case-insensitive) at both pointers.
- If they don’t match, it’s not a palindrome; otherwise, continue until pointers meet.
Note
Time complexity is O(n) where n is the string length. Space complexity is O(1) as it uses constant extra space.