Interview Q&A / Data Structures & Algorithms

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

How do you check if a string is a palindrome, ignoring spaces, punctuation and case?

SHORT ANSWER

Use two pointers from both ends. Skip characters that are not letters or digits, compare the rest in lowercase, and move inward. If any pair differs, it is not a palindrome.

Explain it simply

A palindrome reads the same forwards and backwards, like "Malayalam". For a sentence such as "A man, a plan, a canal: Panama" the spaces and commas should not count.

Put one finger at each end. If a finger sits on punctuation, slide it inward. When both fingers rest on real characters, compare them. If they match, move both inward; if not, stop.

Example

js
function isPalindrome(s) {
  const isAlnum = (c) => /[a-z0-9]/i.test(c);
  let l = 0;
  let r = s.length - 1;
  while (l < r) {
    if (!isAlnum(s[l])) { l++; continue; }
    if (!isAlnum(s[r])) { r--; continue; }
    if (s[l].toLowerCase() !== s[r].toLowerCase()) return false;
    l++;
    r--;
  }
  return true;
}

console.log(isPalindrome("A man, a plan, a canal: Panama")); // Output: true
console.log(isPalindrome("race a car")); // Output: false

Complexity

Time O(n), space O(1).

What to say in the interview

"I use two pointers, skip anything that is not alphanumeric, and compare lowercase characters as I move inward. It is O(n) time and O(1) space. Building a cleaned and reversed copy is simpler but uses O(n) extra memory."

Common mistakes

  • Comparing without lowercasing.
  • Forgetting that the left and right pointers must both skip punctuation.

#strings#two-pointers

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.