← Back to libraryQuestion 151 of 468
🧩JavaScript CodingBeginner

Check if a String is a Palindrome

📌 Definition:

Determine whether a string reads the same forwards and backwards (e.g. "madam", "racecar").

📖 Detailed Explanation:

Compare characters from both ends moving inward with two pointers — O(n) time, O(1) extra space. A common follow-up ignores case, spaces, and punctuation (a 'sentence palindrome').

💻 Solutions:
function isPalindrome(s) {
  let i = 0, j = s.length - 1;
  while (i < j) {
    if (s[i] !== s[j]) return false;
    i++; j--;
  }
  return true;
}
// Sentence variant: normalize first
const isClean = (s) => {
  const c = s.toLowerCase().replace(/[^a-z0-9]/g, '');
  return c === [...c].reverse().join('');
};
🔑 Key Points:
  • Two pointers from both ends → O(1) extra space
  • Normalize case/whitespace for the sentence variant
  • Empty and single-char strings are palindromes
  • Avoid split-reverse-join when O(1) space matters
🌍 Real-World Example:

Palindrome logic appears when validating symmetric tokens, but its real value is demonstrating clean two-pointer traversal and edge-case thinking.

🎯 Scenario-Based Interview Question:

isPalindrome passes for 'madam' but fails 'Race car'. Why, and how do you fix it?