Check if a string is a palindrome (ignoring case and non-alphanumeric characters)
cs-jun-007
Your answer
Answer as you would in a real interview — explain your thinking, not just the conclusion.
Model answer
I use two pointers starting at opposite ends and move inward, skipping non-alphanumeric characters using char.IsLetterOrDigit. At each position, compare the characters case-insensitively with char.ToLowerInvariant. If any pair mismatches, return false. If the pointers meet, return true. This is O(n) time and O(1) space — no string allocation needed, unlike normalising to a new string first.
Code example
public bool IsPalindrome(string s)
{
int left = 0, right = s.Length - 1;
while (left < right)
{
while (left < right && !char.IsLetterOrDigit(s[left])) left++;
while (left < right && !char.IsLetterOrDigit(s[right])) right--;
if (char.ToLowerInvariant(s[left]) != char.ToLowerInvariant(s[right]))
return false;
left++; right--;
}
return true;
}
// Tests
Console.WriteLine(IsPalindrome("A man, a plan, a canal: Panama")); // true
Console.WriteLine(IsPalindrome("race a car")); // false
Follow-up
How would you check if an integer is a palindrome without converting it to a string?