← Back to JavaScript, page 6

javascript-0112 · Easy fresher

How do you check whether a string or a number is a palindrome, and how would you find the longest palindromic substring?

Normalize the text, then compare characters from both ends moving inwards with two pointers, which is O(n) time and O(1) extra space, or compare it with its reverse. For numbers, reverse the digits arithmetically. For the longest palindromic substring, expand around each center, which is O(n squared).

Full answer

A palindrome reads the same forwards and backwards. First clarify the rules. Do case, spaces, and punctuation count? A common version ignores them: "A man, a plan, a canal: Panama" is a palindrome.

Simple version: normalize (lowercase, keep only letters and digits), then compare with the reversed text: clean === [...clean].reverse().join(''). It is easy to read and uses extra memory.

Two pointer version: set left = 0 and right = length - 1, compare, and move inwards until they meet. It stops early on the first mismatch and needs no extra string. If you must skip punctuation without a separate cleaning step, move each pointer past characters that are not letters or digits.

Numbers: a negative number is not a palindrome because of the sign. A fast way avoids strings: reverse the number with reversed = reversed * 10 + n % 10 and compare. The string approach String(n) === [...String(n)].reverse().join('') is acceptable in an interview if you say so.

Longest palindromic substring: every palindrome has a center, either one character (odd length) or the gap between two characters (even length). For each of the 2n - 1 centers, expand outwards while the characters match, and remember the longest. The time is O(n squared), which is acceptable for typical inputs. Manacher's algorithm gets O(n), and is rarely expected.

Unicode: reversing by code unit breaks emoji and accented letters. Use [...text] for code points, and normalize('NFC'), and mention grapheme clusters (Intl.Segmenter) when asked about perfect handling.

javascript
const normalize = (text) => text.toLowerCase().replace(/[^\p{L}\p{N}]/gu, '');

function isPalindrome(text) {
  const chars = [...normalize(text)];
  for (let left = 0, right = chars.length - 1; left < right; left++, right--) {
    if (chars[left] !== chars[right]) return false;
  }
  return true;
}

function isPalindromeNumber(n) {
  if (n < 0 || !Number.isInteger(n)) return false;
  let reversed = 0;
  for (let rest = n; rest > 0; rest = Math.floor(rest / 10)) reversed = reversed * 10 + (rest % 10);
  return reversed === n;
}

function longestPalindrome(text) {
  let best = '';
  const expand = (left, right) => {
    while (left >= 0 && right < text.length && text[left] === text[right]) {
      left--;
      right++;
    }
    return text.slice(left + 1, right);
  };
  for (let center = 0; center < text.length; center++) {
    for (const candidate of [expand(center, center), expand(center, center + 1)]) {
      if (candidate.length > best.length) best = candidate;
    }
  }
  return best;
}

console.log(isPalindrome('A man, a plan, a canal: Panama'), isPalindrome('race a car'), isPalindrome(''));
console.log(isPalindromeNumber(12321), isPalindromeNumber(123), isPalindromeNumber(-121), isPalindromeNumber(10));
console.log(longestPalindrome('babad'), longestPalindrome('cbbd'), longestPalindrome('a'), JSON.stringify(longestPalindrome('')));
console.log([...'ab\u{1F600}'].reverse().join('') === '\u{1F600}ba', 'ab\u{1F600}'.split('').reverse().join('') === '\u{1F600}ba');

Run with Node.js v24.22.1 as js-112.js; two runs gave identical output. Output: true false true true false false false bab bb a "" true false

Key points

  • Clarify whether case, spaces, and punctuation are ignored, then normalize.
  • Two pointers from both ends: O(n) time, O(1) extra space, stops at the first mismatch.
  • Numbers: negatives are not palindromes; reverse digits with arithmetic.
  • Longest palindromic substring: expand around 2n minus 1 centers, O(n squared).
  • Use code point iteration for Unicode text.

Common mistakes

  • Not normalizing case and punctuation when the problem expects it.
  • Reversing with split('') and breaking emoji.
  • Treating a negative number such as -121 as a palindrome.
  • Checking only the first and last character.

Follow-ups

  • How would you check palindromes without creating a new string?
  • What is the time complexity of expand around center, and what does Manacher's algorithm improve?
  • How would you check whether any permutation of a string is a palindrome?

Tips

  • Ask about case and punctuation first.
  • Present two pointers as the answer that avoids extra memory.
  • Mention that palindromes have odd and even centers.